instance_id
stringlengths
65
198
instance_type
stringclasses
2 values
task_type
stringclasses
1 value
repo_url
stringclasses
21 values
commit
stringlengths
40
40
fm_type
stringclasses
2 values
fm_name
stringlengths
1
93
pyfile_name
stringlengths
5
61
original_code
stringlengths
18
106k
gold_code
stringlengths
17
356k
old_filtered_context
stringlengths
24
362k
old_complete_context
stringlengths
93
363k
new_filtered_context
stringlengths
11
315k
new_complete_context
stringlengths
157
367k
initial_error_log
stringlengths
146
49.4M
gold_summary
stringclasses
723 values
original_summary
stringlengths
123
141
pyfile_path
stringlengths
18
101
unittest_path
stringlengths
18
101
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ ImportError while importing test module '/workspace/test_repo/tests/test_filter_pydantic_sub_model_pv2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ ImportError while importing test module '/workspace/test_repo/tests/test_filter_pydantic_sub_model_pv2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py - NameError: name 'Field' i... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ ImportError while importing test module '/workspace/test_repo/tests/test_filter_pydantic_sub_model_pv2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ ImportError while importing test module '/workspace/test_repo/tests/test_filter_pydantic_sub_model_pv2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _________ ERROR collecting tests/test_filter_pydantic_sub_model_pv2.py _________ ImportError while importing test module '/workspace/test_repo/tests/test_filter_pydantic_sub_model_pv2.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_filter_pydantic_sub_model_pv2.py:5: in <module> from fastapi import Depends, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_filter_pydantic_sub_model_pv2.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 3, 'passed': 3, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_filter_pydantic_sub_model_pv2.py
1_fastapi_callee__routing___prepare_response_content__aea04ee32ee1942e6e1a904527bb8da6ba76abd9
callee
fail-to-pass
https://github.com/fastapi/fastapi
aea04ee32ee1942e6e1a904527bb8da6ba76abd9
function
_prepare_response_content
routing.py
def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res
def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def get_request_handler( dependant: Dependant, body_field: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, by_alias=by_alias, exclude_unset=exclude_unset ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, ) 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: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__get_request_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
function
get_request_handler
routing.py
def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app
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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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_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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__get_websocket_app__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
function
get_websocket_app
routing.py
def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**solved_result.values) return app
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__decorator__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
function
decorator
routing.py
def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func
def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__get_route_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
method
get_route_handler
routing.py
def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, )
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, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 __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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__add_api_route__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
add_api_route
routing.py
def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route)
def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route)
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__api_route__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
api_route
routing.py
def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator
def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__add_api_websocket_route__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
method
add_api_websocket_route
routing.py
def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route)
def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route)
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__websocket__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
method
websocket
routing.py
def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator
def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__include_router__addfa89b0f750abc193f62be8e457fc487b842ee
callee
fail-to-pass
https://github.com/fastapi/fastapi
addfa89b0f750abc193f62be8e457fc487b842ee
method
include_router
routing.py
def include_router(self, router: "APIRouter", *, prefix=""): if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" for route in router.routes: if isinstance(route, APIRoute): self.add_api_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, tags=route.tags, summary=route.summary, description=route.description, operation_id=route.operation_id, deprecated=route.deprecated, response_type=route.response_type, response_description=route.response_description, response_code=route.response_code, response_wrapper=route.response_wrapper, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, )
def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, )
import asyncio import inspect from typing import Callable, List, Type from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.formparsers import UploadFile from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import get_name, request_response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import get_body_field, get_dependant, solve_dependencies from fastapi.encoders import jsonable_encoder def serialize_response(*, field: Field = None, response): if field: errors = [] value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return jsonable_encoder(response) def get_app( dependant: Dependant, body_field: Field = None, response_code: str = 200, response_wrapper: Type[Response] = JSONResponse, response_field: Type[Field] = None, ): is_coroutine = dependant.call and asyncio.iscoroutinefunction( dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: body = None if body_field: if is_body_form: raw_body = await request.form() body = {} for field, value in raw_body.items(): if isinstance(value, UploadFile): body[field] = await value.read() else: body[field] = value else: body = await request.json() values, errors = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response if isinstance(raw_response, BaseModel): return response_wrapper( content=jsonable_encoder(raw_response), status_code=response_code ) errors = [] try: return response_wrapper( content=serialize_response( field=response_field, response=raw_response ), status_code=response_code, ) except Exception as e: errors.append(e) try: response = dict(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) try: response = vars(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) raise ValueError(errors) return app class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags or [] self.summary = summary self.description = description or self.endpoint.__doc__ self.operation_id = operation_id self.deprecated = deprecated self.body_field: Field = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, response_code=self.response_code, response_wrapper=self.response_wrapper, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect from typing import Callable, List, Type from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.formparsers import UploadFile from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import get_name, request_response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import get_body_field, get_dependant, solve_dependencies from fastapi.encoders import jsonable_encoder def serialize_response(*, field: Field = None, response): if field: errors = [] value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return jsonable_encoder(response) def get_app( dependant: Dependant, body_field: Field = None, response_code: str = 200, response_wrapper: Type[Response] = JSONResponse, response_field: Type[Field] = None, ): is_coroutine = dependant.call and asyncio.iscoroutinefunction( dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: body = None if body_field: if is_body_form: raw_body = await request.form() body = {} for field, value in raw_body.items(): if isinstance(value, UploadFile): body[field] = await value.read() else: body[field] = value else: body = await request.json() values, errors = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response if isinstance(raw_response, BaseModel): return response_wrapper( content=jsonable_encoder(raw_response), status_code=response_code ) errors = [] try: return response_wrapper( content=serialize_response( field=response_field, response=raw_response ), status_code=response_code, ) except Exception as e: errors.append(e) try: response = dict(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) try: response = vars(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) raise ValueError(errors) return app class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags or [] self.summary = summary self.description = description or self.endpoint.__doc__ self.operation_id = operation_id self.deprecated = deprecated self.body_field: Field = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, response_code=self.response_code, response_wrapper=self.response_wrapper, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def include_router(self, router: "APIRouter", *, prefix=""): if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" for route in router.routes: if isinstance(route, APIRoute): self.add_api_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, tags=route.tags, summary=route.summary, description=route.description, operation_id=route.operation_id, deprecated=route.deprecated, response_type=route.response_type, response_description=route.response_description, response_code=route.response_code, response_wrapper=route.response_wrapper, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, ) def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__get__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
get
routing.py
def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__put__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
put
routing.py
def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP POST operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP DELETE operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP OPTIONS operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP HEAD operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"]="Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__post__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
post
routing.py
def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP DELETE operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP OPTIONS operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP HEAD operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"]="Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__delete__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
delete
routing.py
def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__options__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
options
routing.py
def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__head__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
head
routing.py
def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__patch__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
patch
routing.py
def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__trace__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
trace
routing.py
def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__routing__on_event__9293795e99afbda07d2744f1eb7d23d2f0ea0154
callee
fail-to-pass
https://github.com/fastapi/fastapi
9293795e99afbda07d2744f1eb7d23d2f0ea0154
method
on_event
routing.py
def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack from enum import Enum, IntEnum from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from pydantic.utils import lenient_issubclass from starlette import routing 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 from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp, Scope from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( res.__config__, "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) 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: try: body: Any = None if body_field: if is_body_form: body = await request.form() stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) 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: raise RequestValidationError( [ErrorWrapper(e, ("body", e.pos))], body=e.doc ) from e except HTTPException: raise except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_args: Dict[str, Any] = {"background": 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 sub_response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if sub_response.status_code: response_args["status_code"] = sub_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, ) 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(sub_response.headers.raw) return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = 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.path_regex, self.path_format, self.param_convertors = compile_path( path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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 self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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 if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] 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}" response_field = create_response_field( name=response_name, type_=model) 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) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) 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, ) 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): def __init__( self, *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack from enum import Enum, IntEnum from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from pydantic.utils import lenient_issubclass from starlette import routing 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 from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp, Scope from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( res.__config__, "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) 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: try: body: Any = None if body_field: if is_body_form: body = await request.form() stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) 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: raise RequestValidationError( [ErrorWrapper(e, ("body", e.pos))], body=e.doc ) from e except HTTPException: raise except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_args: Dict[str, Any] = {"background": 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 sub_response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if sub_response.status_code: response_args["status_code"] = sub_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, ) 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(sub_response.headers.raw) return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = 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.path_regex, self.path_format, self.param_convertors = compile_path( path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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 self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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 if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] 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}" response_field = create_response_field( name=response_name, type_=model) 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) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) 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, ) 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): def __init__( self, *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________ ERROR collecting tests/test_generate_unique_id_function.py __________ ImportError while importing test module '/workspace/test_repo/tests/test_generate_unique_id_function.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_generate_unique_id_function.py:4: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_generate_unique_id_function.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 8, 'passed': 8, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_generate_unique_id_function.py
1_fastapi_callee__param_functions__Query__ca27317b654e8265b8783df22e88a439adf96e8a
callee
fail-to-pass
https://github.com/fastapi/fastapi
ca27317b654e8265b8783df22e88a439adf96e8a
function
Query
param_functions.py
def Query( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Query( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, )
from typing import Any, Callable, Sequence from fastapi import params def Path( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Path( default=default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Query( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Query( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Header( # noqa: N802 default: Any, *, alias: str = None, convert_underscores: bool = True, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Header( default, alias=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, regex=regex, deprecated=deprecated, **extra, ) def Cookie( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Cookie( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Body( # noqa: N802 default: Any, *, embed: bool = False, media_type: str = "application/json", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Body( default, embed=embed, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Form( # noqa: N802 default: Any, *, media_type: str = "application/x-www-form-urlencoded", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Form( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def File( # noqa: N802 default: Any, *, media_type: str = "multipart/form-data", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.File( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Depends(dependency: Callable = None) -> Any: # noqa: N802 return params.Depends(dependency=dependency) def Security( # noqa: N802 dependency: Callable = None, scopes: Sequence[str] = None ) -> Any: return params.Security(dependency=dependency, scopes=scopes)
from typing import Any, Callable, Sequence from fastapi import params def Path( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Path( default=default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Query( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Query( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Header( # noqa: N802 default: Any, *, alias: str = None, convert_underscores: bool = True, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Header( default, alias=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, regex=regex, deprecated=deprecated, **extra, ) def Cookie( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Cookie( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Body( # noqa: N802 default: Any, *, embed: bool = False, media_type: str = "application/json", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Body( default, embed=embed, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Form( # noqa: N802 default: Any, *, media_type: str = "application/x-www-form-urlencoded", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Form( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def File( # noqa: N802 default: Any, *, media_type: str = "multipart/form-data", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.File( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Depends(dependency: Callable = None) -> Any: # noqa: N802 return params.Depends(dependency=dependency) def Security( # noqa: N802 dependency: Callable = None, scopes: Sequence[str] = None ) -> Any: return params.Security(dependency=dependency, scopes=scopes)
from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example from typing_extensions import Annotated, Doc, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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 Security( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, scopes: Annotated[ Optional[Sequence[str]], Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency. The term "scope" comes from the OAuth2 specification, it seems to be intentionaly vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. ) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI Security dependency. The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at `/docs`). It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). **Example** ```python from typing import Annotated from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user app = FastAPI() @app.get("/users/me/items/") async def read_own_items( current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] ): return [{"item_id": "Foo", "owner": current_user.username}] ``` """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example from typing_extensions import Annotated, Doc, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, 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 Body( # 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, embed: Annotated[ Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a key instead of being the JSON body itself. This happens automatically when more than one `Body` parameter is declared. Read more about it in the [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), ] = None, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/json", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Body( default=default, default_factory=default_factory, embed=embed, media_type=media_type, 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 Form( # 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, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/x-www-form-urlencoded", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Form( default=default, default_factory=default_factory, media_type=media_type, 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 File( # 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, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "multipart/form-data", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.File( default=default, default_factory=default_factory, media_type=media_type, 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 Depends( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI dependency. It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). **Example** ```python from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return commons ``` """ return params.Depends(dependency=dependency, use_cache=use_cache) def Security( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, scopes: Annotated[ Optional[Sequence[str]], Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency. The term "scope" comes from the OAuth2 specification, it seems to be intentionaly vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. ) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI Security dependency. The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at `/docs`). It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). **Example** ```python from typing import Annotated from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user app = FastAPI() @app.get("/users/me/items/") async def read_own_items( current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] ): return [{"item_id": "Foo", "owner": current_user.username}] ``` """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 2 items tests/test_ambiguous_params.py::test_no_annotated_defaults PASSED [ 50%] tests/test_ambiguous_params.py::test_multiple_annotations FAILED [100%] =================================== FAILURES =================================== __________________________ test_multiple_annotations ___________________________ def test_multiple_annotations(): async def dep(): pass # pragma: nocover @app.get("/multi-query") > async def get(foo: Annotated[int, Query(gt=2), Query(lt=10)]): E TypeError: Query() missing 1 required positional argument: 'default' tests/test_ambiguous_params.py:38: TypeError =========================== short test summary info ============================ FAILED tests/test_ambiguous_params.py::test_multiple_annotations - TypeError:... ========================= 1 failed, 1 passed in 0.61s ==========================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 1, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
./test_repo/fastapi/param_functions.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__param_functions__Form__ca27317b654e8265b8783df22e88a439adf96e8a
callee
fail-to-pass
https://github.com/fastapi/fastapi
ca27317b654e8265b8783df22e88a439adf96e8a
function
Form
param_functions.py
def Form( # noqa: N802 default: Any, *, media_type: str = "application/x-www-form-urlencoded", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Form( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, )
def Form( # 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, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/x-www-form-urlencoded", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Form( default=default, default_factory=default_factory, media_type=media_type, 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, )
from typing import Any, Callable, Sequence from fastapi import params def Path( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Path( default=default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Query( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Query( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Header( # noqa: N802 default: Any, *, alias: str = None, convert_underscores: bool = True, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Header( default, alias=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, regex=regex, deprecated=deprecated, **extra, ) def Cookie( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Cookie( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Body( # noqa: N802 default: Any, *, embed: bool = False, media_type: str = "application/json", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Body( default, embed=embed, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Form( # noqa: N802 default: Any, *, media_type: str = "application/x-www-form-urlencoded", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Form( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def File( # noqa: N802 default: Any, *, media_type: str = "multipart/form-data", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.File( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Depends(dependency: Callable = None) -> Any: # noqa: N802 return params.Depends(dependency=dependency) def Security( # noqa: N802 dependency: Callable = None, scopes: Sequence[str] = None ) -> Any: return params.Security(dependency=dependency, scopes=scopes)
from typing import Any, Callable, Sequence from fastapi import params def Path( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Path( default=default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Query( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Query( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Header( # noqa: N802 default: Any, *, alias: str = None, convert_underscores: bool = True, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Header( default, alias=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, regex=regex, deprecated=deprecated, **extra, ) def Cookie( # noqa: N802 default: Any, *, alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, deprecated: bool = None, **extra: Any, ) -> Any: return params.Cookie( default, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, deprecated=deprecated, **extra, ) def Body( # noqa: N802 default: Any, *, embed: bool = False, media_type: str = "application/json", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Body( default, embed=embed, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Form( # noqa: N802 default: Any, *, media_type: str = "application/x-www-form-urlencoded", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.Form( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def File( # noqa: N802 default: Any, *, media_type: str = "multipart/form-data", alias: str = None, title: str = None, description: str = None, gt: float = None, ge: float = None, lt: float = None, le: float = None, min_length: int = None, max_length: int = None, regex: str = None, **extra: Any, ) -> Any: return params.File( default, media_type=media_type, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, regex=regex, **extra, ) def Depends(dependency: Callable = None) -> Any: # noqa: N802 return params.Depends(dependency=dependency) def Security( # noqa: N802 dependency: Callable = None, scopes: Sequence[str] = None ) -> Any: return params.Security(dependency=dependency, scopes=scopes)
from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example from typing_extensions import Annotated, Doc, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, 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 Body( # 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, embed: Annotated[ Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a key instead of being the JSON body itself. This happens automatically when more than one `Body` parameter is declared. Read more about it in the [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), ] = None, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/json", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Body( default=default, default_factory=default_factory, embed=embed, media_type=media_type, 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 Security( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, scopes: Annotated[ Optional[Sequence[str]], Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency. The term "scope" comes from the OAuth2 specification, it seems to be intentionaly vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. ) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI Security dependency. The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at `/docs`). It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). **Example** ```python from typing import Annotated from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user app = FastAPI() @app.get("/users/me/items/") async def read_own_items( current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] ): return [{"item_id": "Foo", "owner": current_user.username}] ``` """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example from typing_extensions import Annotated, Doc, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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, 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 Body( # 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, embed: Annotated[ Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a key instead of being the JSON body itself. This happens automatically when more than one `Body` parameter is declared. Read more about it in the [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), ] = None, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/json", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Body( default=default, default_factory=default_factory, embed=embed, media_type=media_type, 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 Form( # 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, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/x-www-form-urlencoded", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.Form( default=default, default_factory=default_factory, media_type=media_type, 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 File( # 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, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "multipart/form-data", 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, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Annotated[ Union[str, 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.File( default=default, default_factory=default_factory, media_type=media_type, 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 Depends( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI dependency. It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). **Example** ```python from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return commons ``` """ return params.Depends(dependency=dependency, use_cache=use_cache) def Security( # noqa: N802 dependency: Annotated[ Optional[Callable[..., Any]], Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. """ ), ] = None, *, scopes: Annotated[ Optional[Sequence[str]], Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency. The term "scope" comes from the OAuth2 specification, it seems to be intentionaly vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. ) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. """ ), ] = True, ) -> Any: """ Declare a FastAPI Security dependency. The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI and the automatic UI docs (by default at `/docs`). It takes a single "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you. Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). **Example** ```python from typing import Annotated from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user app = FastAPI() @app.get("/users/me/items/") async def read_own_items( current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] ): return [{"item_id": "Foo", "owner": current_user.username}] ``` """ return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:34: in <module> from fastapi.dependencies.models import Dependant fastapi/dependencies/models.py:4: in <module> from fastapi.security.base import SecurityBase fastapi/security/__init__.py:9: in <module> from .oauth2 import OAuth2 as OAuth2 fastapi/security/oauth2.py:16: in <module> class OAuth2PasswordRequestForm: fastapi/security/oauth2.py:66: in OAuth2PasswordRequestForm Form(pattern="password"), E TypeError: Form() missing 1 required positional argument: 'default' =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py - TypeError: Form() missing 1 required p... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/param_functions.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_ambiguous_params.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_ambiguous_params.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.63s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py - NameError: name 'Field' is not defined !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_ambiguous_params.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_ambiguous_params.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _______________ ERROR collecting tests/test_ambiguous_params.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_ambiguous_params.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_ambiguous_params.py:2: in <module> from fastapi import Depends, FastAPI, Path fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_ambiguous_params.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_ambiguous_params.py
1_fastapi_callee__utils__get_param_sub_dependant__e92b43b5c826ffc2109e813cbbca7875cdc13bbc
callee
fail-to-pass
https://github.com/fastapi/fastapi
e92b43b5c826ffc2109e813cbbca7875cdc13bbc
function
get_param_sub_dependant
utils.py
def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, )
def get_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, )
import asyncio import inspect from copy import deepcopy from datetime import date, datetime, time, timedelta from decimal import Decimal from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, ) from uuid import UUID from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request param_supported_types = ( str, int, float, bool, UUID, date, datetime, time, timedelta, Decimal, ) sequence_shapes = {Shape.LIST, Shape.SET, Shape.TUPLE} sequence_types = (list, set, tuple) sequence_shape_to_type = {Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple} def get_flat_dependant(dependant: Dependant) -> Dependant: 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert ( lenient_issubclass(param.annotation, param_supported_types) or param.annotation == param.empty ), f"Path params must be of one of the supported types" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif ( param.default == param.empty or param.default is None or isinstance(param.default, param_supported_types) ) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: origin = getattr(param.annotation, "__origin__", None) param_all_types = param_supported_types + (list, tuple, set) if isinstance(param.default, (params.Query, params.Header)): assert lenient_issubclass( param.annotation, param_all_types ) or lenient_issubclass( origin, param_all_types ), f"Parameters for Query and Header must be of type str, int, float, bool, list, tuple or set: {param}" else: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path and Cookies must be of type str, int, float, bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param_name elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema: Type[Schema] = params.Param, force_type: params.ParamTypes = None, ) -> None: default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant) -> None: default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None, background_tasks: BackgroundTasks = None, ) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks]]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors, background_tasks = await solve_dependencies( request=request, dependant=sub_dependant, body=body, background_tasks=background_tasks, ) if sub_errors: errors.extend(sub_errors) continue assert sub_dependant.call is not None, "sub_dependant.call must be a function" if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) if sub_dependant.name is not None: values[sub_dependant.name] = 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_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.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) return values, errors, background_tasks def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if field.shape in sequence_shapes and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) else: value = received_params.get(field.alias) schema: params.Param = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: if field.shape in sequence_shapes and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from datetime import date, datetime, time, timedelta from decimal import Decimal from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, ) from uuid import UUID from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request param_supported_types = ( str, int, float, bool, UUID, date, datetime, time, timedelta, Decimal, ) sequence_shapes = {Shape.LIST, Shape.SET, Shape.TUPLE} sequence_types = (list, set, tuple) sequence_shape_to_type = {Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple} def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant def get_flat_dependant(dependant: Dependant) -> Dependant: 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert ( lenient_issubclass(param.annotation, param_supported_types) or param.annotation == param.empty ), f"Path params must be of one of the supported types" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif ( param.default == param.empty or param.default is None or isinstance(param.default, param_supported_types) ) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: origin = getattr(param.annotation, "__origin__", None) param_all_types = param_supported_types + (list, tuple, set) if isinstance(param.default, (params.Query, params.Header)): assert lenient_issubclass( param.annotation, param_all_types ) or lenient_issubclass( origin, param_all_types ), f"Parameters for Query and Header must be of type str, int, float, bool, list, tuple or set: {param}" else: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path and Cookies must be of type str, int, float, bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param_name elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema: Type[Schema] = params.Param, force_type: params.ParamTypes = None, ) -> None: default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant) -> None: default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None, background_tasks: BackgroundTasks = None, ) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks]]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors, background_tasks = await solve_dependencies( request=request, dependant=sub_dependant, body=body, background_tasks=background_tasks, ) if sub_errors: errors.extend(sub_errors) continue assert sub_dependant.call is not None, "sub_dependant.call must be a function" if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) if sub_dependant.name is not None: values[sub_dependant.name] = 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_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.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) return values, errors, background_tasks def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if field.shape in sequence_shapes and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) else: value = received_params.get(field.alias) schema: params.Param = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: if field.shape in sequence_shapes and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_sub_dependant__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_sub_dependant
utils.py
def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant
def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_flat_dependant__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_flat_dependant
utils.py
def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant
def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_typed_signature__d8fe307d61a55148a4d95c550f0ef33148ba8681
callee
fail-to-pass
https://github.com/fastapi/fastapi
d8fe307d61a55148a4d95c550f0ef33148ba8681
function
get_typed_signature
utils.py
def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import ForwardRef, evaluate_forwardref, lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field.schema, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: Field) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type # type: ignore else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = ( solved_result ) sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if field.shape in sequence_shapes and isinstance( received_body, FormData ): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default=None) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(set(body_param_media_types)) == 1: BodySchema_kwargs["media_type"] = body_param_media_types[0] field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import ForwardRef, evaluate_forwardref, lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field.schema, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: Field) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type # type: ignore else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = ( solved_result ) sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if field.shape in sequence_shapes and isinstance( received_body, FormData ): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default=None) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(set(body_param_media_types)) == 1: BodySchema_kwargs["media_type"] = body_param_media_types[0] field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_typed_annotation__d8fe307d61a55148a4d95c550f0ef33148ba8681
callee
fail-to-pass
https://github.com/fastapi/fastapi
d8fe307d61a55148a4d95c550f0ef33148ba8681
function
get_typed_annotation
utils.py
def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation
def get_typed_annotation(annotation: Any, globalns: Dict[str, Any]) -> Any: if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import ForwardRef, evaluate_forwardref, lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field.schema, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: Field) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type # type: ignore else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = ( solved_result ) sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if field.shape in sequence_shapes and isinstance( received_body, FormData ): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default=None) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(set(body_param_media_types)) == 1: BodySchema_kwargs["media_type"] = body_param_media_types[0] field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import ForwardRef, evaluate_forwardref, lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: if not ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field.schema, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: Field) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type # type: ignore else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache = ( solved_result ) sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if field.shape in sequence_shapes and isinstance( received_body, FormData ): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodySchema_kwargs: Dict[str, Any] = dict(default=None) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body body_param_media_types = [ getattr(f.schema, "media_type") for f in flat_dependant.body_params if isinstance(f.schema, params.Body) ] if len(set(body_param_media_types)) == 1: BodySchema_kwargs["media_type"] = body_param_media_types[0] field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(**BodySchema_kwargs), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_dependant__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_dependant
utils.py
def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant
def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant default_schema = params.Path, force_type = params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__add_non_field_param_to_dependency__bd407cc4ed81b21e4287735b7d31a30a452e3a9d
callee
fail-to-pass
https://github.com/fastapi/fastapi
bd407cc4ed81b21e4287735b7d31a30a452e3a9d
function
add_non_field_param_to_dependency
utils.py
def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None
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
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant def get_flat_dependant(dependant: Dependant) -> Dependant: 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: return ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not isinstance(field.schema, params.Body) ) def is_scalar_sequence_field(field: Field) -> bool: if field.shape in sequence_shapes and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True return False def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Dict[str, Any] = None, background_tasks: BackgroundTasks = None, ) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks]]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors, background_tasks = await solve_dependencies( request=request, dependant=sub_dependant, body=body, background_tasks=background_tasks, ) if sub_errors: errors.extend(sub_errors) continue assert sub_dependant.call is not None, "sub_dependant.call must be a function" if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) if sub_dependant.name is not None: values[sub_dependant.name] = 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) return values, errors, background_tasks def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if field.shape in sequence_shapes and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema: params.Param = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: if field.shape in sequence_shapes and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import get_path_param_names from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required, Shape from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.websockets import WebSocket sequence_shapes = { Shape.LIST, Shape.SET, Shape.TUPLE, Shape.SEQUENCE, Shape.TUPLE_ELLIPS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { Shape.LIST: list, Shape.SET: set, Shape.TUPLE: tuple, Shape.SEQUENCE: list, Shape.TUPLE_ELLIPS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant def get_flat_dependant(dependant: Dependant) -> Dependant: 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def is_scalar_field(field: Field) -> bool: return ( field.shape == Shape.SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not isinstance(field.schema, params.Body) ) def is_scalar_sequence_field(field: Field) -> bool: if field.shape in sequence_shapes and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True return False def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field(param=param, default_schema=params.Query) if param_name in path_param_names: assert param.default == param.empty or isinstance( param.default, params.Path ), "Path params must have no defaults or use Path(...)" assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" param_field = get_param_field( param=param, default_schema=params.Path, force_type=params.ParamTypes.path, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: assert isinstance( param_field.schema, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, default_schema: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ) -> Field: default_value = Required had_schema = False if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): had_schema = True schema = default_value default_value = schema.default if isinstance(schema, params.Param) and getattr(schema, "in_", None) is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) if not schema.alias and getattr(schema, "convert_underscores", None): alias = param.name.replace("_", "-") else: alias = schema.alias or param.name field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, model_config=BaseConfig, class_validators={}, schema=schema, ) if not had_schema and not is_scalar_field(field=field): field.schema = params.Body(schema.default) return field def add_param_to_fields(*, field: Field, dependant: Dependant) -> None: field.schema = cast(params.Param, field.schema) if field.schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif field.schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif field.schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( field.schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {field.name}" dependant.cookie_params.append(field) def is_coroutine_callable(call: Callable) -> bool: if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Dict[str, Any] = None, background_tasks: BackgroundTasks = None, ) -> Tuple[Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks]]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors, background_tasks = await solve_dependencies( request=request, dependant=sub_dependant, body=body, background_tasks=background_tasks, ) if sub_errors: errors.extend(sub_errors) continue assert sub_dependant.call is not None, "sub_dependant.call must be a function" if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) if sub_dependant.name is not None: values[sub_dependant.name] = 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) return values, errors, background_tasks def request_params_to_args( required_params: Sequence[Field], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if field.shape in sequence_shapes and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) schema: params.Param = field.schema assert isinstance( schema, params.Param), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(schema.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(schema.in_.value, field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: if field.shape in sequence_shapes and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: value = received_body.get(field.alias) if ( value is None or (isinstance(field.schema, params.Form) and value == "") or ( isinstance(field.schema, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field.schema, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_schema_compatible_field(*, field: Field) -> Field: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = Field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, schema=field.schema, ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[Field]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return get_schema_compatible_field(field=first_param) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema: Type[params.Body] = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators={}, alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__analyze_param__375513f11494bc3499050ad2a0d378fb6e37ca98
callee
fail-to-pass
https://github.com/fastapi/fastapi
375513f11494bc3499050ad2a0d378fb6e37ca98
function
analyze_param
utils.py
def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, ) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: field_info = None used_default_field_info = False depends = None type_annotation: Any = Any if ( annotation is not inspect.Signature.empty # type: ignore[comparison-overlap] and get_origin(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)) ] assert ( len(fastapi_annotations) <= 1 ), f"Cannot specify multiple `Annotated` FastAPI arguments for {param_name!r}" fastapi_annotation = next(iter(fastapi_annotations), None) if isinstance(fastapi_annotation, FieldInfo): field_info = fastapi_annotation assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation elif annotation is not inspect.Signature.empty: type_annotation = annotation 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 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 if depends is not None and depends.dependency is None: depends.dependency = type_annotation if lenient_issubclass( type_annotation, (Request, WebSocket, HTTPConnection, Response, BackgroundTasks, 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}" elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else Required if is_path_param: # We might check here that `default_value is Required`, 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() else: field_info = params.Query(default=default_value) used_default_field_info = True field = None if field_info is not None: 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 annotation = get_annotation_from_field_info( annotation if annotation is not inspect.Signature.empty else Any, field_info, param_name, ) 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 = create_response_field( name=param_name, type_=annotation, default=field_info.default, alias=alias, required=field_info.default in (Required, Undefined), field_info=field_info, ) if used_default_field_info: if lenient_issubclass(field.type_, UploadFile): field.field_info = params.File(field_info.default) elif not is_scalar_field(field=field): field.field_info = params.Body(field_info.default) return type_annotation, depends, field
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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) return ParamDetails(type_annotation=type_annotation, depends=depends, field=field)
import dataclasses import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi.concurrency import ( AsyncExitStack, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import create_response_field, get_path_param_names from pydantic import BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import ( SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, Undefined, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import evaluate_forwardref, get_args, get_origin from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket from typing_extensions import Annotated sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } 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 check_file_field(field: ModelField) -> None: field_info = field.field_info if isinstance(field_info, params.Form): try: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not dataclasses.is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names type_annotation, depends, param_field = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) if depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=depends, path=path, security_scopes=security_scopes, ) dependant.dependencies.append(sub_dependant) continue if add_non_field_param_to_dependency( param_name=param_name, type_annotation=type_annotation, dependant=dependant, ): assert ( param_field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue assert param_field is not None if is_body_param(param_field=param_field, is_path_param=is_path_param): dependant.body_params.append(param_field) else: add_param_to_fields(field=param_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, BackgroundTasks): 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 default_value = value if value is not inspect.Signature.empty else Required if is_path_param: # We might check here that `default_value is Required`, 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() else: field_info = params.Query(default=default_value) used_default_field_info = True field = None if field_info is not None: 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 annotation = get_annotation_from_field_info( annotation if annotation is not inspect.Signature.empty else Any, field_info, param_name, ) 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 = create_response_field( name=param_name, type_=annotation, default=field_info.default, alias=alias, required=field_info.default in (Required, Undefined), field_info=field_info, ) if used_default_field_info: if lenient_issubclass(field.type_, UploadFile): field.field_info = params.File(field_info.default) elif not is_scalar_field(field=field): field.field_info = params.Body(field_info.default) return type_annotation, depends, field def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: if is_path_param: assert is_scalar_field( field=param_field ), "Path params must be of one of the supported types" return False elif is_scalar_field(field=param_field): return False elif isinstance( param_field.field_info, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): return False else: assert isinstance( param_field.field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body()" return True def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, field.field_info) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: Optional[BackgroundTasks] = None, response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable[..., Any], Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) ( sub_values, sub_errors, background_tasks, _, # the subdependency returns the same response we have sub_dependency_cache, ) = solved_result dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) solved = await solve_generator( call=call, stack=stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = field.field_info assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = field.field_info embed = getattr(field_info, "embed", None) field_alias_omitted = len(required_params) == 1 and not embed if field_alias_omitted: received_body = {field.alias: received_body} for field in required_params: loc: Tuple[str, ...] if field_alias_omitted: loc = ("body",) else: loc = ("body", field.alias) value: Optional[Any] = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(loc)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(loc)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]] ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = sequence_shape_to_type[field.shape](results) v_, errors_ = field.validate(value, values, loc=loc) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorWrapper: missing_field_error = ErrorWrapper(MissingError(), loc=loc) return missing_field_error def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = first_param.field_info embed = getattr(field_info, "embed", None) body_param_names_set = {param.name for param in flat_dependant.body_params} if len(body_param_names_set) == 1 and not embed: check_file_field(first_param) return first_param # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(param.field_info, "embed", True) # noqa: B010 model_name = "Body_" + name BodyModel: Type[BaseModel] = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = {"default": None} if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) check_file_field(final_field) return final_field
import dataclasses import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi.concurrency import ( AsyncExitStack, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import create_response_field, get_path_param_names from pydantic import BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import ( SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, Undefined, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import evaluate_forwardref, get_args, get_origin from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket from typing_extensions import Annotated sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } 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 check_file_field(field: ModelField) -> None: field_info = field.field_info if isinstance(field_info, params.Form): try: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not dataclasses.is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names type_annotation, depends, param_field = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) if depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=depends, path=path, security_scopes=security_scopes, ) dependant.dependencies.append(sub_dependant) continue if add_non_field_param_to_dependency( param_name=param_name, type_annotation=type_annotation, dependant=dependant, ): assert ( param_field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue assert param_field is not None if is_body_param(param_field=param_field, is_path_param=is_path_param): dependant.body_params.append(param_field) else: add_param_to_fields(field=param_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, BackgroundTasks): 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 def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, ) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: field_info = None used_default_field_info = False depends = None type_annotation: Any = Any if ( annotation is not inspect.Signature.empty # type: ignore[comparison-overlap] and get_origin(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)) ] assert ( len(fastapi_annotations) <= 1 ), f"Cannot specify multiple `Annotated` FastAPI arguments for {param_name!r}" fastapi_annotation = next(iter(fastapi_annotations), None) if isinstance(fastapi_annotation, FieldInfo): field_info = fastapi_annotation assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation elif annotation is not inspect.Signature.empty: type_annotation = annotation 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 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 if depends is not None and depends.dependency is None: depends.dependency = type_annotation if lenient_issubclass( type_annotation, (Request, WebSocket, HTTPConnection, Response, BackgroundTasks, 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}" elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else Required if is_path_param: # We might check here that `default_value is Required`, 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() else: field_info = params.Query(default=default_value) used_default_field_info = True field = None if field_info is not None: 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 annotation = get_annotation_from_field_info( annotation if annotation is not inspect.Signature.empty else Any, field_info, param_name, ) 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 = create_response_field( name=param_name, type_=annotation, default=field_info.default, alias=alias, required=field_info.default in (Required, Undefined), field_info=field_info, ) if used_default_field_info: if lenient_issubclass(field.type_, UploadFile): field.field_info = params.File(field_info.default) elif not is_scalar_field(field=field): field.field_info = params.Body(field_info.default) return type_annotation, depends, field def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: if is_path_param: assert is_scalar_field( field=param_field ), "Path params must be of one of the supported types" return False elif is_scalar_field(field=param_field): return False elif isinstance( param_field.field_info, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): return False else: assert isinstance( param_field.field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body()" return True def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, field.field_info) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: Optional[BackgroundTasks] = None, response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable[..., Any], Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) ( sub_values, sub_errors, background_tasks, _, # the subdependency returns the same response we have sub_dependency_cache, ) = solved_result dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) solved = await solve_generator( call=call, stack=stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = field.field_info assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = field.field_info embed = getattr(field_info, "embed", None) field_alias_omitted = len(required_params) == 1 and not embed if field_alias_omitted: received_body = {field.alias: received_body} for field in required_params: loc: Tuple[str, ...] if field_alias_omitted: loc = ("body",) else: loc = ("body", field.alias) value: Optional[Any] = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(loc)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(loc)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]] ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = sequence_shape_to_type[field.shape](results) v_, errors_ = field.validate(value, values, loc=loc) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorWrapper: missing_field_error = ErrorWrapper(MissingError(), loc=loc) return missing_field_error def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = first_param.field_info embed = getattr(field_info, "embed", None) body_param_names_set = {param.name for param in flat_dependant.body_params} if len(body_param_names_set) == 1 and not embed: check_file_field(first_param) return first_param # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(param.field_info, "embed", True) # noqa: B010 model_name = "Body_" + name BodyModel: Type[BaseModel] = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = {"default": None} if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) check_file_field(final_field) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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] default_value = value if value is not inspect.Signature.empty else Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__add_param_to_fields__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
add_param_to_fields
utils.py
def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(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)
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__is_coroutine_callable__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
is_coroutine_callable
utils.py
def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call)
def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call)
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__is_async_gen_callable__b90bf2da9ee5870a45591a10c4c8ac4af76d12f1
callee
fail-to-pass
https://github.com/fastapi/fastapi
b90bf2da9ee5870a45591a10c4c8ac4af76d12f1
function
is_async_gen_callable
utils.py
def is_async_gen_callable(call: Callable) -> bool: if inspect.isasyncgenfunction(call): return True call = getattr(call, "__call__", None) return inspect.isasyncgenfunction(call)
def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call)
import asyncio import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.concurrency import ( AsyncExitStack, _fake_asynccontextmanager, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import ( PYDANTIC_1, create_response_field, get_field_info, get_path_param_names, ) from pydantic import BaseConfig, BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket try: from pydantic.fields import ( SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import ForwardRef, evaluate_forwardref except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic.fields import Required, Shape # type: ignore from pydantic import Schema as FieldInfo # type: ignore from pydantic.schema import get_annotation_from_schema # type: ignore from pydantic.utils import ForwardRef, evaluate_forwardref # type: ignore SHAPE_LIST = Shape.LIST SHAPE_SEQUENCE = Shape.SEQUENCE SHAPE_SET = Shape.SET SHAPE_SINGLETON = Shape.SINGLETON SHAPE_TUPLE = Shape.TUPLE SHAPE_TUPLE_ELLIPSIS = Shape.TUPLE_ELLIPS def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Type[Any]: return get_annotation_from_schema(annotation, field_info) sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = get_field_info(field) if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation async_contextmanager_dependencies_error = """ FastAPI dependencies with yield require Python 3.7 or above, or the backports for Python 3.6, installed with: pip install async-exit-stack async-generator """ def check_dependency_contextmanagers() -> None: if AsyncExitStack is None or asynccontextmanager == _fake_asynccontextmanager: raise RuntimeError( async_contextmanager_dependencies_error) # pragma: no cover def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters if is_gen_callable(call) or is_async_gen_callable(call): check_dependency_contextmanagers() dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field( param=param, default_field_info=params.Query, param_name=param_name ) if param_name in path_param_names: assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" if isinstance(param.default, params.Path): ignore_default = False else: ignore_default = True param_field = get_param_field( param=param, param_name=param_name, default_field_info=params.Path, force_type=params.ParamTypes.path, ignore_default=ignore_default, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: field_info = get_field_info(param_field) assert isinstance( field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, param_name: str, default_field_info: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ignore_default: bool = False, ) -> ModelField: default_value = Required had_schema = False if not param.default == param.empty and ignore_default is False: default_value = param.default if isinstance(default_value, FieldInfo): had_schema = True field_info = default_value default_value = field_info.default if ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = default_field_info.in_ if force_type: field_info.in_ = force_type # type: ignore else: field_info = default_field_info(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_field_info( annotation, field_info, param_name) 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 = create_response_field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, field_info=field_info, ) field.required = required if not had_schema and not is_scalar_field(field=field): if PYDANTIC_1: field.field_info = params.Body(field_info.default) else: # type: ignore # pragma: nocover field.schema = params.Body(field_info.default) return field def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, get_field_info(field)) 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) def is_coroutine_callable(call: Callable) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return inspect.iscoroutinefunction(call) def is_gen_callable(call: Callable) -> bool: if inspect.isgeneratorfunction(call): return True call = getattr(call, "__call__", None) return inspect.isgeneratorfunction(call) async def solve_generator( *, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): if not inspect.isasyncgenfunction(call): # asynccontextmanager from the async_generator backfill pre python3.7 # does not support callables that are not functions or methods. # See https://github.com/python-trio/async_generator/issues/32 # # Expand the callable class into its __call__ method before decorating it. # This approach will work on newer python versions as well. call = getattr(call, "__call__", None) cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) ( sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache, ) = solved_result sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): stack = request.scope.get("fastapi_astack") if stack is None: raise RuntimeError( async_contextmanager_dependencies_error ) # pragma: no cover solved = await solve_generator( call=call, stack=stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = get_field_info(field) assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: if PYDANTIC_1: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: # pragma: nocover errors.append( ErrorWrapper( # type: ignore MissingError(), loc=(field_info.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(field.alias)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(field.alias)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(field_alias: str) -> ErrorWrapper: if PYDANTIC_1: missing_field_error = ErrorWrapper( MissingError(), loc=("body", field_alias)) else: # pragma: no cover missing_field_error = ErrorWrapper( # type: ignore MissingError(), loc=("body", field_alias), config=BaseConfig, ) return missing_field_error def get_schema_compatible_field(*, field: ModelField) -> ModelField: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = create_response_field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info if PYDANTIC_1 else field.schema, # type: ignore ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = get_field_info(first_param) embed = getattr(field_info, "embed", None) body_param_names_set = set( [param.name for param in flat_dependant.body_params]) if len(body_param_names_set) == 1 and not embed: return get_schema_compatible_field(field=first_param) # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(get_field_info(param), "embed", True) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = dict(default=None) if any( isinstance(get_field_info(f), params.File) for f in flat_dependant.body_params ): BodyFieldInfo: Type[params.Body] = params.File elif any( isinstance(get_field_info(f), params.Form) for f in flat_dependant.body_params ): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ getattr(get_field_info(f), "media_type") for f in flat_dependant.body_params if isinstance(get_field_info(f), params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] return create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), )
import asyncio import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.concurrency import ( AsyncExitStack, _fake_asynccontextmanager, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import ( PYDANTIC_1, create_response_field, get_field_info, get_path_param_names, ) from pydantic import BaseConfig, BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket try: from pydantic.fields import ( SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import ForwardRef, evaluate_forwardref except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic.fields import Required, Shape # type: ignore from pydantic import Schema as FieldInfo # type: ignore from pydantic.schema import get_annotation_from_schema # type: ignore from pydantic.utils import ForwardRef, evaluate_forwardref # type: ignore SHAPE_LIST = Shape.LIST SHAPE_SEQUENCE = Shape.SEQUENCE SHAPE_SET = Shape.SET SHAPE_SINGLETON = Shape.SINGLETON SHAPE_TUPLE = Shape.TUPLE SHAPE_TUPLE_ELLIPSIS = Shape.TUPLE_ELLIPS def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Type[Any]: return get_annotation_from_schema(annotation, field_info) sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = get_field_info(field) if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation async_contextmanager_dependencies_error = """ FastAPI dependencies with yield require Python 3.7 or above, or the backports for Python 3.6, installed with: pip install async-exit-stack async-generator """ def check_dependency_contextmanagers() -> None: if AsyncExitStack is None or asynccontextmanager == _fake_asynccontextmanager: raise RuntimeError( async_contextmanager_dependencies_error) # pragma: no cover def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters if is_gen_callable(call) or is_async_gen_callable(call): check_dependency_contextmanagers() dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field( param=param, default_field_info=params.Query, param_name=param_name ) if param_name in path_param_names: assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" if isinstance(param.default, params.Path): ignore_default = False else: ignore_default = True param_field = get_param_field( param=param, param_name=param_name, default_field_info=params.Path, force_type=params.ParamTypes.path, ignore_default=ignore_default, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: field_info = get_field_info(param_field) assert isinstance( field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, param_name: str, default_field_info: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ignore_default: bool = False, ) -> ModelField: default_value = Required had_schema = False if not param.default == param.empty and ignore_default is False: default_value = param.default if isinstance(default_value, FieldInfo): had_schema = True field_info = default_value default_value = field_info.default if ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = default_field_info.in_ if force_type: field_info.in_ = force_type # type: ignore else: field_info = default_field_info(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_field_info( annotation, field_info, param_name) 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 = create_response_field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, field_info=field_info, ) field.required = required if not had_schema and not is_scalar_field(field=field): if PYDANTIC_1: field.field_info = params.Body(field_info.default) else: # type: ignore # pragma: nocover field.schema = params.Body(field_info.default) return field def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, get_field_info(field)) 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) def is_coroutine_callable(call: Callable) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return inspect.iscoroutinefunction(call) def is_async_gen_callable(call: Callable) -> bool: if inspect.isasyncgenfunction(call): return True call = getattr(call, "__call__", None) return inspect.isasyncgenfunction(call) def is_gen_callable(call: Callable) -> bool: if inspect.isgeneratorfunction(call): return True call = getattr(call, "__call__", None) return inspect.isgeneratorfunction(call) async def solve_generator( *, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): if not inspect.isasyncgenfunction(call): # asynccontextmanager from the async_generator backfill pre python3.7 # does not support callables that are not functions or methods. # See https://github.com/python-trio/async_generator/issues/32 # # Expand the callable class into its __call__ method before decorating it. # This approach will work on newer python versions as well. call = getattr(call, "__call__", None) cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) ( sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache, ) = solved_result sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): stack = request.scope.get("fastapi_astack") if stack is None: raise RuntimeError( async_contextmanager_dependencies_error ) # pragma: no cover solved = await solve_generator( call=call, stack=stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = get_field_info(field) assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: if PYDANTIC_1: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: # pragma: nocover errors.append( ErrorWrapper( # type: ignore MissingError(), loc=(field_info.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(field.alias)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(field.alias)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(field_alias: str) -> ErrorWrapper: if PYDANTIC_1: missing_field_error = ErrorWrapper( MissingError(), loc=("body", field_alias)) else: # pragma: no cover missing_field_error = ErrorWrapper( # type: ignore MissingError(), loc=("body", field_alias), config=BaseConfig, ) return missing_field_error def get_schema_compatible_field(*, field: ModelField) -> ModelField: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = create_response_field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info if PYDANTIC_1 else field.schema, # type: ignore ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = get_field_info(first_param) embed = getattr(field_info, "embed", None) body_param_names_set = set( [param.name for param in flat_dependant.body_params]) if len(body_param_names_set) == 1 and not embed: return get_schema_compatible_field(field=first_param) # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(get_field_info(param), "embed", True) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = dict(default=None) if any( isinstance(get_field_info(f), params.File) for f in flat_dependant.body_params ): BodyFieldInfo: Type[params.Body] = params.File elif any( isinstance(get_field_info(f), params.Form) for f in flat_dependant.body_params ): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ getattr(get_field_info(f), "media_type") for f in flat_dependant.body_params if isinstance(get_field_info(f), params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] return create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), )
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.63s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__is_gen_callable__b90bf2da9ee5870a45591a10c4c8ac4af76d12f1
callee
fail-to-pass
https://github.com/fastapi/fastapi
b90bf2da9ee5870a45591a10c4c8ac4af76d12f1
function
is_gen_callable
utils.py
def is_gen_callable(call: Callable) -> bool: if inspect.isgeneratorfunction(call): return True call = getattr(call, "__call__", None) return inspect.isgeneratorfunction(call)
def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call)
import asyncio import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.concurrency import ( AsyncExitStack, _fake_asynccontextmanager, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import ( PYDANTIC_1, create_response_field, get_field_info, get_path_param_names, ) from pydantic import BaseConfig, BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket try: from pydantic.fields import ( SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import ForwardRef, evaluate_forwardref except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic.fields import Required, Shape # type: ignore from pydantic import Schema as FieldInfo # type: ignore from pydantic.schema import get_annotation_from_schema # type: ignore from pydantic.utils import ForwardRef, evaluate_forwardref # type: ignore SHAPE_LIST = Shape.LIST SHAPE_SEQUENCE = Shape.SEQUENCE SHAPE_SET = Shape.SET SHAPE_SINGLETON = Shape.SINGLETON SHAPE_TUPLE = Shape.TUPLE SHAPE_TUPLE_ELLIPSIS = Shape.TUPLE_ELLIPS def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Type[Any]: return get_annotation_from_schema(annotation, field_info) sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = get_field_info(field) if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation async_contextmanager_dependencies_error = """ FastAPI dependencies with yield require Python 3.7 or above, or the backports for Python 3.6, installed with: pip install async-exit-stack async-generator """ def check_dependency_contextmanagers() -> None: if AsyncExitStack is None or asynccontextmanager == _fake_asynccontextmanager: raise RuntimeError( async_contextmanager_dependencies_error) # pragma: no cover def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters if is_gen_callable(call) or is_async_gen_callable(call): check_dependency_contextmanagers() dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field( param=param, default_field_info=params.Query, param_name=param_name ) if param_name in path_param_names: assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" if isinstance(param.default, params.Path): ignore_default = False else: ignore_default = True param_field = get_param_field( param=param, param_name=param_name, default_field_info=params.Path, force_type=params.ParamTypes.path, ignore_default=ignore_default, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: field_info = get_field_info(param_field) assert isinstance( field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, param_name: str, default_field_info: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ignore_default: bool = False, ) -> ModelField: default_value = Required had_schema = False if not param.default == param.empty and ignore_default is False: default_value = param.default if isinstance(default_value, FieldInfo): had_schema = True field_info = default_value default_value = field_info.default if ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = default_field_info.in_ if force_type: field_info.in_ = force_type # type: ignore else: field_info = default_field_info(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_field_info( annotation, field_info, param_name) 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 = create_response_field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, field_info=field_info, ) field.required = required if not had_schema and not is_scalar_field(field=field): if PYDANTIC_1: field.field_info = params.Body(field_info.default) else: # type: ignore # pragma: nocover field.schema = params.Body(field_info.default) return field def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, get_field_info(field)) 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) def is_coroutine_callable(call: Callable) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return inspect.iscoroutinefunction(call) def is_async_gen_callable(call: Callable) -> bool: if inspect.isasyncgenfunction(call): return True call = getattr(call, "__call__", None) return inspect.isasyncgenfunction(call) def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = get_field_info(field) assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: if PYDANTIC_1: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: # pragma: nocover errors.append( ErrorWrapper( # type: ignore MissingError(), loc=(field_info.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(field.alias)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(field.alias)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(field_alias: str) -> ErrorWrapper: if PYDANTIC_1: missing_field_error = ErrorWrapper( MissingError(), loc=("body", field_alias)) else: # pragma: no cover missing_field_error = ErrorWrapper( # type: ignore MissingError(), loc=("body", field_alias), config=BaseConfig, ) return missing_field_error def get_schema_compatible_field(*, field: ModelField) -> ModelField: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = create_response_field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info if PYDANTIC_1 else field.schema, # type: ignore ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = get_field_info(first_param) embed = getattr(field_info, "embed", None) body_param_names_set = set( [param.name for param in flat_dependant.body_params]) if len(body_param_names_set) == 1 and not embed: return get_schema_compatible_field(field=first_param) # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(get_field_info(param), "embed", True) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = dict(default=None) if any( isinstance(get_field_info(f), params.File) for f in flat_dependant.body_params ): BodyFieldInfo: Type[params.Body] = params.File elif any( isinstance(get_field_info(f), params.Form) for f in flat_dependant.body_params ): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ getattr(get_field_info(f), "media_type") for f in flat_dependant.body_params if isinstance(get_field_info(f), params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] return create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), )
import asyncio import inspect from contextlib import contextmanager from copy import deepcopy from typing import ( Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) from fastapi import params from fastapi.concurrency import ( AsyncExitStack, _fake_asynccontextmanager, asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import ( PYDANTIC_1, create_response_field, get_field_info, get_path_param_names, ) from pydantic import BaseConfig, BaseModel, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from starlette.background import BackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import FormData, Headers, QueryParams, UploadFile from starlette.requests import Request from starlette.responses import Response from starlette.websockets import WebSocket try: from pydantic.fields import ( SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, FieldInfo, ModelField, Required, ) from pydantic.schema import get_annotation_from_field_info from pydantic.typing import ForwardRef, evaluate_forwardref except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic.fields import Required, Shape # type: ignore from pydantic import Schema as FieldInfo # type: ignore from pydantic.schema import get_annotation_from_schema # type: ignore from pydantic.utils import ForwardRef, evaluate_forwardref # type: ignore SHAPE_LIST = Shape.LIST SHAPE_SEQUENCE = Shape.SEQUENCE SHAPE_SET = Shape.SET SHAPE_SINGLETON = Shape.SINGLETON SHAPE_TUPLE = Shape.TUPLE SHAPE_TUPLE_ELLIPSIS = Shape.TUPLE_ELLIPS def get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Type[Any]: return get_annotation_from_schema(annotation, field_info) sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_types = (list, set, tuple) sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } def get_param_sub_dependant( *, param: inspect.Parameter, path: str, security_scopes: List[str] = None ) -> Dependant: depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation return get_sub_dependant( depends=depends, dependency=dependency, path=path, name=param.name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable, path: str, name: str = None, security_scopes: List[str] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) sub_dependant.security_scopes = security_scopes return sub_dependant CacheKey = Tuple[Optional[Callable], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: List[CacheKey] = None ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_schemes=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def is_scalar_field(field: ModelField) -> bool: field_info = get_field_info(field) if not ( field.shape == SHAPE_SINGLETON and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, sequence_types + (dict,)) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: if not all(is_scalar_field(f) for f in field.sub_fields): return False return True def is_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( field.type_, BaseModel ): if field.sub_fields is not None: for sub_field in field.sub_fields: if not is_scalar_field(sub_field): return False return True if lenient_issubclass(field.type_, sequence_types): return True return False def get_typed_signature(call: Callable) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any: annotation = param.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) return annotation async_contextmanager_dependencies_error = """ FastAPI dependencies with yield require Python 3.7 or above, or the backports for Python 3.6, installed with: pip install async-exit-stack async-generator """ def check_dependency_contextmanagers() -> None: if AsyncExitStack is None or asynccontextmanager == _fake_asynccontextmanager: raise RuntimeError( async_contextmanager_dependencies_error) # pragma: no cover def get_dependant( *, path: str, call: Callable, name: str = None, security_scopes: List[str] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters if is_gen_callable(call) or is_async_gen_callable(call): check_dependency_contextmanagers() dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( param=param, path=path, security_scopes=security_scopes ) dependant.dependencies.append(sub_dependant) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): continue if add_non_field_param_to_dependency(param=param, dependant=dependant): continue param_field = get_param_field( param=param, default_field_info=params.Query, param_name=param_name ) if param_name in path_param_names: assert is_scalar_field( field=param_field ), f"Path params must be of one of the supported types" if isinstance(param.default, params.Path): ignore_default = False else: ignore_default = True param_field = get_param_field( param=param, param_name=param_name, default_field_info=params.Path, force_type=params.ParamTypes.path, ignore_default=ignore_default, ) add_param_to_fields(field=param_field, dependant=dependant) elif is_scalar_field(field=param_field): add_param_to_fields(field=param_field, dependant=dependant) elif isinstance( param.default, (params.Query, params.Header) ) and is_scalar_sequence_field(param_field): add_param_to_fields(field=param_field, dependant=dependant) else: field_info = get_field_info(param_field) assert isinstance( field_info, params.Body ), f"Param: {param_field.name} can only be a request body, using Body(...)" dependant.body_params.append(param_field) return dependant def add_non_field_param_to_dependency( *, param: inspect.Parameter, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(param.annotation, Request): dependant.request_param_name = param.name return True elif lenient_issubclass(param.annotation, WebSocket): dependant.websocket_param_name = param.name return True elif lenient_issubclass(param.annotation, Response): dependant.response_param_name = param.name return True elif lenient_issubclass(param.annotation, BackgroundTasks): dependant.background_tasks_param_name = param.name return True elif lenient_issubclass(param.annotation, SecurityScopes): dependant.security_scopes_param_name = param.name return True return None def get_param_field( *, param: inspect.Parameter, param_name: str, default_field_info: Type[params.Param] = params.Param, force_type: params.ParamTypes = None, ignore_default: bool = False, ) -> ModelField: default_value = Required had_schema = False if not param.default == param.empty and ignore_default is False: default_value = param.default if isinstance(default_value, FieldInfo): had_schema = True field_info = default_value default_value = field_info.default if ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = default_field_info.in_ if force_type: field_info.in_ = force_type # type: ignore else: field_info = default_field_info(default_value) required = default_value == Required annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_field_info( annotation, field_info, param_name) 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 = create_response_field( name=param.name, type_=annotation, default=None if required else default_value, alias=alias, required=required, field_info=field_info, ) field.required = required if not had_schema and not is_scalar_field(field=field): if PYDANTIC_1: field.field_info = params.Body(field_info.default) else: # type: ignore # pragma: nocover field.schema = params.Body(field_info.default) return field def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = cast(params.Param, get_field_info(field)) 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) def is_coroutine_callable(call: Callable) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) return inspect.iscoroutinefunction(call) def is_async_gen_callable(call: Callable) -> bool: if inspect.isasyncgenfunction(call): return True call = getattr(call, "__call__", None) return inspect.isasyncgenfunction(call) def is_gen_callable(call: Callable) -> bool: if inspect.isgeneratorfunction(call): return True call = getattr(call, "__call__", None) return inspect.isgeneratorfunction(call) async def solve_generator( *, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): if not inspect.isasyncgenfunction(call): # asynccontextmanager from the async_generator backfill pre python3.7 # does not support callables that are not functions or methods. # See https://github.com/python-trio/async_generator/issues/32 # # Expand the callable class into its __call__ method before decorating it. # This approach will work on newer python versions as well. call = getattr(call, "__call__", None) cm = asynccontextmanager(call)(**sub_values) return await stack.enter_async_context(cm) async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[Dict[str, Any], FormData]] = None, background_tasks: BackgroundTasks = None, response: Response = None, dependency_overrides_provider: Any = None, dependency_cache: Dict[Tuple[Callable, Tuple[str]], Any] = None, ) -> Tuple[ Dict[str, Any], List[ErrorWrapper], Optional[BackgroundTasks], Response, Dict[Tuple[Callable, Tuple[str]], Any], ]: values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] response = response or Response( content=None, status_code=None, # type: ignore headers=None, media_type=None, background=None, ) dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable, sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable, Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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, ) ( sub_values, sub_errors, background_tasks, sub_response, sub_dependency_cache, ) = solved_result sub_response = cast(Response, sub_response) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code dependency_cache.update(sub_dependency_cache) if sub_errors: errors.extend(sub_errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): stack = request.scope.get("fastapi_astack") if stack is None: raise RuntimeError( async_contextmanager_dependencies_error ) # pragma: no cover solved = await solve_generator( call=call, stack=stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) else: solved = await run_in_threadpool(call, **sub_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 required_params=dependant.body_params, received_body=body ) values.update(body_values) errors.extend(body_errors) 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.security_scopes ) return values, errors, background_tasks, response, dependency_cache def request_params_to_args( required_params: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: if is_scalar_sequence_field(field) and isinstance( received_params, (QueryParams, Headers) ): value = received_params.getlist(field.alias) or field.default else: value = received_params.get(field.alias) field_info = get_field_info(field) assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" if value is None: if field.required: if PYDANTIC_1: errors.append( ErrorWrapper( MissingError(), loc=(field_info.in_.value, field.alias) ) ) else: # pragma: nocover errors.append( ErrorWrapper( # type: ignore MissingError(), loc=(field_info.in_.value, field.alias), config=BaseConfig, ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field_info.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] field_info = get_field_info(field) embed = getattr(field_info, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value: Any = None if received_body is not None: if ( field.shape in sequence_shapes or field.type_ in sequence_types ) and isinstance(received_body, FormData): value = received_body.getlist(field.alias) else: try: value = received_body.get(field.alias) except AttributeError: errors.append(get_missing_field_error(field.alias)) continue if ( value is None or (isinstance(field_info, params.Form) and value == "") or ( isinstance(field_info, params.Form) and field.shape in sequence_shapes and len(value) == 0 ) ): if field.required: errors.append(get_missing_field_error(field.alias)) else: values[field.name] = deepcopy(field.default) continue if ( isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, UploadFile) ): value = await value.read() elif ( field.shape in sequence_shapes and isinstance(field_info, params.File) and lenient_issubclass(field.type_, bytes) and isinstance(value, sequence_types) ): awaitables = [sub_value.read() for sub_value in value] contents = await asyncio.gather(*awaitables) value = sequence_shape_to_type[field.shape](contents) v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_missing_field_error(field_alias: str) -> ErrorWrapper: if PYDANTIC_1: missing_field_error = ErrorWrapper( MissingError(), loc=("body", field_alias)) else: # pragma: no cover missing_field_error = ErrorWrapper( # type: ignore MissingError(), loc=("body", field_alias), config=BaseConfig, ) return missing_field_error def get_schema_compatible_field(*, field: ModelField) -> ModelField: out_field = field if lenient_issubclass(field.type_, UploadFile): use_type: type = bytes if field.shape in sequence_shapes: use_type = List[bytes] out_field = create_response_field( name=field.name, type_=use_type, class_validators=field.class_validators, model_config=field.model_config, default=field.default, required=field.required, alias=field.alias, field_info=field.field_info if PYDANTIC_1 else field.schema, # type: ignore ) return out_field def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] field_info = get_field_info(first_param) embed = getattr(field_info, "embed", None) body_param_names_set = set( [param.name for param in flat_dependant.body_params]) if len(body_param_names_set) == 1 and not embed: return get_schema_compatible_field(field=first_param) # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field # That is combined (embedded) with other body fields for param in flat_dependant.body_params: setattr(get_field_info(param), "embed", True) model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = get_schema_compatible_field(field=f) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = dict(default=None) if any( isinstance(get_field_info(f), params.File) for f in flat_dependant.body_params ): BodyFieldInfo: Type[params.Body] = params.File elif any( isinstance(get_field_info(f), params.Form) for f in flat_dependant.body_params ): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ getattr(get_field_info(f), "media_type") for f in flat_dependant.body_params if isinstance(get_field_info(f), params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] return create_response_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), )
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) 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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__request_params_to_args__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
request_params_to_args
utils.py
def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors
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 = [] 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, field.alias) 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
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils___should_embed_body_fields__aa21814a89853c17c139054a5c51f0bb1ea68a0a
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa21814a89853c17c139054a5c51f0bb1ea68a0a
function
_should_embed_body_fields
utils.py
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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form): return True return False
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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import create_model_field, get_path_param_names 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect from fastapi.utils import create_model_field, get_path_param_names 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) values[field.name] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body if isinstance(received_body, FormData): body_to_process = await _extract_form_body(body_fields, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__get_body_field__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_body_field
utils.py
def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
def get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors default = None, required = required, model_config = BaseConfig, class_validators = [], alias = "body", schema = BodySchema(None), ) return field
import asyncio import inspect from copy import deepcopy from typing import Any, Callable, Dict, List, Tuple from starlette.concurrency import run_in_threadpool from starlette.requests import Request from fastapi import params from fastapi.dependencies.models import Dependant, SecurityRequirement from fastapi.security.base import SecurityBase from fastapi.utils import get_path_param_names from pydantic import BaseConfig, Schema, create_model from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic.utils import lenient_issubclass param_supported_types = (str, int, float, bool) def get_sub_dependant(*, param: inspect.Parameter, path: str): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(depends, params.Security) and isinstance(dependency, SecurityBase): security_requirement = SecurityRequirement( security_scheme=dependency, scopes=depends.scopes ) sub_dependant.security_requirements.append(security_requirement) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_requirements.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_dependant(*, path: str, call: Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ) or param.annotation == param.empty, f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig(), class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def is_coroutine_callable(call: Callable = None): if not call: return False if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) if inspect.isclass(call): return False call = getattr(call, "__call__", None) if not call: return False return asyncio.iscoroutinefunction(call) async def solve_dependencies( *, request: Request, dependant: Dependant, body: Dict[str, Any] = None ): values: Dict[str, Any] = {} errors: List[ErrorWrapper] = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant, body=body ) if sub_errors: return {}, errors if sub_dependant.call and is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[ sub_dependant.name ] = solved # type: ignore # Sub-dependants always have a name 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( # type: ignore # body_params checked above dependant.body_params, body ) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def request_params_to_args( required_params: List[Field], received_params: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors async def request_body_to_args( required_params: List[Field], received_body: Dict[str, Any] ) -> Tuple[Dict[str, Any], List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] embed = getattr(field.schema, "embed", None) if len(required_params) == 1 and not embed: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field(*, dependant: Dependant, name: str): flat_dependant = get_flat_dependant(dependant) if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] embed = getattr(first_param.schema, "embed", None) if len(flat_dependant.body_params) == 1 and not embed: return first_param model_name = "Body_" + name BodyModel = create_model(model_name) for f in flat_dependant.body_params: BodyModel.__fields__[f.name] = f required = any(True for f in flat_dependant.body_params if f.required) if any(isinstance(f.schema, params.File) for f in flat_dependant.body_params): BodySchema = params.File elif any(isinstance(f.schema, params.Form) for f in flat_dependant.body_params): BodySchema = params.Form else: BodySchema = params.Body field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=BodySchema(None), ) return field
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend( flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, Required, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, get_missing_field_error, get_model_fields, 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, SecurityRequirement from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect 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 Annotated, 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: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import parse_options_header # type: ignore 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_param_sub_dependant( *, param_name: str, depends: params.Depends, path: str, security_scopes: Optional[List[str]] = None, ) -> Dependant: assert depends.dependency return get_sub_dependant( depends=depends, dependency=depends.dependency, path=path, name=param_name, security_scopes=security_scopes, ) def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable( depends.dependency ), "A parameter-less dependency must have a callable dependency" return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) def get_sub_dependant( *, depends: params.Depends, dependency: Callable[..., Any], path: str, name: Optional[str] = None, security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None security_scopes = security_scopes or [] if isinstance(depends, params.Security): dependency_scopes = depends.scopes security_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): use_scopes = security_scopes security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) sub_dependant = get_dependant( path=path, call=dependency, name=name, security_scopes=security_scopes, use_cache=depends.use_cache, ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) return sub_dependant CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[List[CacheKey]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) 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(), security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) 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 ) 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.security_requirements.extend(flat_sub.security_requirements) return flat_dependant def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = inspect.signature(call) globalns = getattr(call, "__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) return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = inspect.signature(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(call, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, security_scopes: Optional[List[str]] = None, use_cache: bool = True, ) -> Dependant: path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters dependant = Dependant( call=call, name=name, path=path, security_scopes=security_scopes, use_cache=use_cache, ) 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: sub_dependant = get_param_sub_dependant( param_name=param_name, depends=param_details.depends, path=path, security_scopes=security_scopes, ) 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, annotation=use_annotation ) assert field_info.default is Undefined or field_info.default is Required, ( 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 = Required # 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 if PYDANTIC_V2: 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.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 Required if is_path_param: # We might check here that `default_value is Required`, 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 = get_annotation_from_field_info( use_annotation, field_info, param_name, ) 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 (Required, 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) 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) def is_coroutine_callable(call: Callable[..., Any]) -> bool: if inspect.isroutine(call): return inspect.iscoroutinefunction(call) if inspect.isclass(call): return False dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.iscoroutinefunction(dunder_call) def is_async_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isasyncgenfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isasyncgenfunction(dunder_call) def is_gen_callable(call: Callable[..., Any]) -> bool: if inspect.isgeneratorfunction(call): return True dunder_call = getattr(call, "__call__", None) # noqa: B004 return inspect.isgeneratorfunction(dunder_call) async def solve_generator( *, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any] ) -> Any: if is_gen_callable(call): cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values)) elif is_async_gen_callable(call): cm = asynccontextmanager(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[Tuple[Callable[..., Any], Tuple[str]], 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[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore dependency_cache = dependency_cache or {} sub_dependant: Dependant for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) sub_dependant.cache_key = cast( Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key ) 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, security_scopes=sub_dependant.security_scopes, ) 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 dependency_cache.update(solved_result.dependency_cache) 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 is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): 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.security_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_, ErrorWrapper): return None, [errors_] elif 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]) -> Any: if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(field.alias) else: value = values.get(field.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 = [] 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, field.alias) 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 _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 to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( first_field.type_, BaseModel ): return True return False async def _extract_form_body( body_fields: List[ModelField], received_body: FormData, ) -> Dict[str, Any]: values = {} first_field = body_fields[0] first_field_info = first_field.field_info for field in body_fields: value = _get_multidict_value(field, received_body) if ( isinstance(first_field_info, params.File) and is_bytes_field(field) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_field(field) and isinstance(first_field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) # type: ignore[arg-type] results: List[Union[bytes, str]] = [] async def process_fn( fn: Callable[[], Coroutine[Any, Any, Any]], ) -> None: result = await fn() results.append(result) # noqa: B023 async with anyio.create_task_group() as tg: for sub_value in value: tg.start_soon(process_fn, sub_value.read) value = serialize_sequence_value(field=field, value=results) if value is not None: values[field.name] = value for key, value in received_body.items(): if key not in values: values[key] = value return values async def request_body_to_args( body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: List[ModelField] = body_fields if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_model_fields(first_field.type_) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: Tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", field.alias) value: Optional[Any] = None if body_to_process is not None: try: value = body_to_process.get(field.alias) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue 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 get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> Optional[ModelField]: """ Get a ModelField representing the request body for a path operation, combining all body parameters into a single field if necessary. Used to check if it's form data (with `isinstance(body_field, params.Form)`) or JSON and to generate the JSON Schema for a request body. This is **not** used to validate/parse the request body, that's done with each individual body parameter. """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any(True for f in flat_dependant.body_params if f.required) BodyFieldInfo_kwargs: Dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: Type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_multipart_installation.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_multipart_installation.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_multipart_installation.py:2: in <module> from fastapi import FastAPI, File, Form, UploadFile fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:23: in <module> from fastapi._compat import ( E ImportError: cannot import name 'get_model_fields' from 'fastapi._compat' (/workspace/test_repo/fastapi/_compat.py) =========================== short test summary info ============================ ERROR tests/test_multipart_installation.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/dependencies/utils.py
./test_repo/tests/test_multipart_installation.py
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_computed_fields.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_computed_fields.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_computed_fields.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_computed_fields.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_computed_fields.py - NameError: name 'Field' is not defined !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_computed_fields.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_computed_fields.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_computed_fields.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_computed_fields.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ________________ ERROR collecting tests/test_computed_fields.py ________________ ImportError while importing test module '/workspace/test_repo/tests/test_computed_fields.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_computed_fields.py:2: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_computed_fields.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_computed_fields.py
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ ImportError while importing test module '/workspace/test_repo/tests/test_datetime_custom_encoder.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ ImportError while importing test module '/workspace/test_repo/tests/test_datetime_custom_encoder.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py - NameError: name 'Field' is not ... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ ImportError while importing test module '/workspace/test_repo/tests/test_datetime_custom_encoder.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ ImportError while importing test module '/workspace/test_repo/tests/test_datetime_custom_encoder.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_datetime_custom_encoder.py ____________ ImportError while importing test module '/workspace/test_repo/tests/test_datetime_custom_encoder.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_datetime_custom_encoder.py:3: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_datetime_custom_encoder.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_datetime_custom_encoder.py
1_fastapi_callee___compat__get_schema_from_model_field__0976185af96ab2ee39c949c0456be616b01f8669
callee
fail-to-pass
https://github.com/fastapi/fastapi
0976185af96ab2ee39c949c0456be616b01f8669
function
get_schema_from_model_field
_compat.py
def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return is_bytes_sequence_annotation(field.type_) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return type(field_info).from_annotation(annotation) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = ( get_origin( field.field_info.annotation) or field.field_info.annotation ) # type: ignore[arg-type] assert issubclass(origin_type, sequence_types) # type: ignore[no-any-return] return sequence_annotation_to_type[origin_type](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors()[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 else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.networks import ( # type: ignore[no-redef] MultiHostDsn as MultiHostUrl, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: # type: ignore[no-any-return,attr-defined] return sequence_shape_to_type[field.shape](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper( MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel 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 _normalize_errors(errors) ] return updated_loc_errors 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: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] 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: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return 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 ) assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] 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]: return [ ModelField(field_info=field_info, name=name) for name, field_info in model.model_fields.items() ] else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] for sub_field in field.sub_fields: # type: ignore[attr-defined] if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return list(model.__fields__.values()) # type: ignore[attr-defined] 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 _normalize_errors(errors) ] return updated_loc_errors 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)) # type: ignore[arg-type] 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)) 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) )
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 2 items tests/test_custom_schema_fields.py::test_custom_response_schema FAILED [ 50%] tests/test_custom_schema_fields.py::test_response PASSED [100%] =================================== FAILURES =================================== _________________________ test_custom_response_schema __________________________ def test_custom_response_schema(): > response = client.get("/openapi.json") tests/test_custom_schema_fields.py:51: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:551: in get return super().get( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1041: in get return self.request( ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:519: in request return super().request( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:814: in request return self.send(request, auth=auth, follow_redirects=follow_redirects) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:901: in send response = self._send_handling_auth( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:929: in _send_handling_auth response = self._send_handling_redirects( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:966: in _send_handling_redirects response = self._send_single_request(request) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1002: in _send_single_request response = transport.handle_request(request) ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:401: in handle_request raise exc ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:398: in handle_request portal.call(self.app, scope, receive, send) ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:277: in call return cast(T_Retval, self.start_task_soon(func, *args).result()) /usr/local/lib/python3.11/concurrent/futures/_base.py:456: in result return self.__get_result() /usr/local/lib/python3.11/concurrent/futures/_base.py:401: in __get_result raise self._exception ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:217: in _call_func retval = await retval fastapi/applications.py:1054: in __call__ await super().__call__(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/applications.py:123: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:186: in __call__ raise exc ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:164: in __call__ await self.app(scope, receive, _send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py:65: in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:754: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:774: in app await route.handle(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:295: in handle await self.app(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:77: in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:74: in app response = await f(request) fastapi/applications.py:1009: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:981: in openapi self.openapi_schema = get_openapi( fastapi/openapi/utils.py:483: in get_openapi result = get_openapi_path( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def get_openapi_path( *, route: routing.APIRoute, operation_ids: Set[str], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], 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) all_route_params = get_flat_params(route.dependant) operation_parameters = get_openapi_operation_parameters( all_route_params=all_route_params, schema_generator=schema_generator, 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, schema_generator=schema_generator, 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, schema_generator=schema_generator, 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, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) E TypeError: get_schema_from_model_field() got an unexpected keyword argument 'separate_input_output_schemas' fastapi/openapi/utils.py:322: TypeError =========================== short test summary info ============================ FAILED tests/test_custom_schema_fields.py::test_custom_response_schema - Type... ========================= 1 failed, 1 passed in 0.86s ==========================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 1, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
./test_repo/fastapi/_compat.py
./test_repo/tests/test_custom_schema_fields.py
1_fastapi_callee___compat__get_definitions__0976185af96ab2ee39c949c0456be616b01f8669
callee
fail-to-pass
https://github.com/fastapi/fastapi
0976185af96ab2ee39c949c0456be616b01f8669
function
get_definitions
_compat.py
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return is_bytes_sequence_annotation(field.type_) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return type(field_info).from_annotation(annotation) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = ( get_origin( field.field_info.annotation) or field.field_info.annotation ) # type: ignore[arg-type] assert issubclass(origin_type, sequence_types) # type: ignore[no-any-return] return sequence_annotation_to_type[origin_type](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors()[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 else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.networks import ( # type: ignore[no-redef] MultiHostDsn as MultiHostUrl, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: # type: ignore[no-any-return,attr-defined] return sequence_shape_to_type[field.shape](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper( MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel 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 _normalize_errors(errors) ] return updated_loc_errors 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: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] 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: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return 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 ) assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] 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]: return [ ModelField(field_info=field_info, name=name) for name, field_info in model.model_fields.items() ] else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] for sub_field in field.sub_fields: # type: ignore[attr-defined] if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return list(model.__fields__.values()) # type: ignore[attr-defined] 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 _normalize_errors(errors) ] return updated_loc_errors 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)) # type: ignore[arg-type] 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)) 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) )
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 2 items tests/test_custom_schema_fields.py::test_custom_response_schema FAILED [ 50%] tests/test_custom_schema_fields.py::test_response PASSED [100%] =================================== FAILURES =================================== _________________________ test_custom_response_schema __________________________ def test_custom_response_schema(): > response = client.get("/openapi.json") tests/test_custom_schema_fields.py:51: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:551: in get return super().get( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1041: in get return self.request( ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:519: in request return super().request( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:814: in request return self.send(request, auth=auth, follow_redirects=follow_redirects) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:901: in send response = self._send_handling_auth( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:929: in _send_handling_auth response = self._send_handling_redirects( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:966: in _send_handling_redirects response = self._send_single_request(request) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1002: in _send_single_request response = transport.handle_request(request) ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:401: in handle_request raise exc ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:398: in handle_request portal.call(self.app, scope, receive, send) ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:277: in call return cast(T_Retval, self.start_task_soon(func, *args).result()) /usr/local/lib/python3.11/concurrent/futures/_base.py:456: in result return self.__get_result() /usr/local/lib/python3.11/concurrent/futures/_base.py:401: in __get_result raise self._exception ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:217: in _call_func retval = await retval fastapi/applications.py:1054: in __call__ await super().__call__(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/applications.py:123: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:186: in __call__ raise exc ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:164: in __call__ await self.app(scope, receive, _send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py:65: in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:754: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:774: in app await route.handle(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:295: in handle await self.app(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:77: in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:74: in app response = await f(request) fastapi/applications.py:1009: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:981: in openapi self.openapi_schema = get_openapi( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, ) -> 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) schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) > field_mapping, definitions = get_definitions( fields=all_fields, schema_generator=schema_generator, model_name_map=model_name_map, separate_input_output_schemas=separate_input_output_schemas, ) E TypeError: get_definitions() got an unexpected keyword argument 'separate_input_output_schemas' fastapi/openapi/utils.py:475: TypeError =========================== short test summary info ============================ FAILED tests/test_custom_schema_fields.py::test_custom_response_schema - Type... ========================= 1 failed, 1 passed in 0.85s ==========================
{'total': 2, 'passed': 2, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 1, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
./test_repo/fastapi/_compat.py
./test_repo/tests/test_custom_schema_fields.py
1_fastapi_callee__routing___prepare_response_content__aea04ee32ee1942e6e1a904527bb8da6ba76abd9
callee
fail-to-pass
https://github.com/fastapi/fastapi
aea04ee32ee1942e6e1a904527bb8da6ba76abd9
function
_prepare_response_content
routing.py
def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res
def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def get_request_handler( dependant: Dependant, body_field: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, by_alias=by_alias, exclude_unset=exclude_unset ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, ) 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: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__get_request_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
function
get_request_handler
routing.py
def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app
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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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_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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__get_websocket_app__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
function
get_websocket_app
routing.py
def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**solved_result.values) return app
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__decorator__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
function
decorator
routing.py
def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func
def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__get_route_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
method
get_route_handler
routing.py
def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, )
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, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 __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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__add_api_route__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
add_api_route
routing.py
def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route)
def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route)
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__api_route__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
api_route
routing.py
def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator
def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__add_api_websocket_route__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
method
add_api_websocket_route
routing.py
def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route)
def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route)
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__websocket__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
method
websocket
routing.py
def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator
def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__include_router__addfa89b0f750abc193f62be8e457fc487b842ee
callee
fail-to-pass
https://github.com/fastapi/fastapi
addfa89b0f750abc193f62be8e457fc487b842ee
method
include_router
routing.py
def include_router(self, router: "APIRouter", *, prefix=""): if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" for route in router.routes: if isinstance(route, APIRoute): self.add_api_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, tags=route.tags, summary=route.summary, description=route.description, operation_id=route.operation_id, deprecated=route.deprecated, response_type=route.response_type, response_description=route.response_description, response_code=route.response_code, response_wrapper=route.response_wrapper, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, )
def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, )
import asyncio import inspect from typing import Callable, List, Type from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.formparsers import UploadFile from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import get_name, request_response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import get_body_field, get_dependant, solve_dependencies from fastapi.encoders import jsonable_encoder def serialize_response(*, field: Field = None, response): if field: errors = [] value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return jsonable_encoder(response) def get_app( dependant: Dependant, body_field: Field = None, response_code: str = 200, response_wrapper: Type[Response] = JSONResponse, response_field: Type[Field] = None, ): is_coroutine = dependant.call and asyncio.iscoroutinefunction( dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: body = None if body_field: if is_body_form: raw_body = await request.form() body = {} for field, value in raw_body.items(): if isinstance(value, UploadFile): body[field] = await value.read() else: body[field] = value else: body = await request.json() values, errors = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response if isinstance(raw_response, BaseModel): return response_wrapper( content=jsonable_encoder(raw_response), status_code=response_code ) errors = [] try: return response_wrapper( content=serialize_response( field=response_field, response=raw_response ), status_code=response_code, ) except Exception as e: errors.append(e) try: response = dict(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) try: response = vars(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) raise ValueError(errors) return app class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags or [] self.summary = summary self.description = description or self.endpoint.__doc__ self.operation_id = operation_id self.deprecated = deprecated self.body_field: Field = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, response_code=self.response_code, response_wrapper=self.response_wrapper, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect from typing import Callable, List, Type from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.formparsers import UploadFile from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import get_name, request_response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import get_body_field, get_dependant, solve_dependencies from fastapi.encoders import jsonable_encoder def serialize_response(*, field: Field = None, response): if field: errors = [] value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return jsonable_encoder(response) def get_app( dependant: Dependant, body_field: Field = None, response_code: str = 200, response_wrapper: Type[Response] = JSONResponse, response_field: Type[Field] = None, ): is_coroutine = dependant.call and asyncio.iscoroutinefunction( dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: body = None if body_field: if is_body_form: raw_body = await request.form() body = {} for field, value in raw_body.items(): if isinstance(value, UploadFile): body[field] = await value.read() else: body[field] = value else: body = await request.json() values, errors = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response if isinstance(raw_response, BaseModel): return response_wrapper( content=jsonable_encoder(raw_response), status_code=response_code ) errors = [] try: return response_wrapper( content=serialize_response( field=response_field, response=raw_response ), status_code=response_code, ) except Exception as e: errors.append(e) try: response = dict(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) try: response = vars(raw_response) return response_wrapper( content=serialize_response( field=response_field, response=response), status_code=response_code, ) except Exception as e: errors.append(e) raise ValueError(errors) return app class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags or [] self.summary = summary self.description = description or self.endpoint.__doc__ self.operation_id = operation_id self.deprecated = deprecated self.body_field: Field = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, response_code=self.response_code, response_wrapper=self.response_wrapper, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: List[str] = None, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def include_router(self, router: "APIRouter", *, prefix=""): if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" for route in router.routes: if isinstance(route, APIRoute): self.add_api_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, tags=route.tags, summary=route.summary, description=route.description, operation_id=route.operation_id, deprecated=route.deprecated, response_type=route.response_type, response_description=route.response_description, response_code=route.response_code, response_wrapper=route.response_wrapper, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, name=route.name, include_in_schema=route.include_in_schema, ) def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: List[str] = None, summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags or [], summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__get__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
get
routing.py
def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__put__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
put
routing.py
def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP POST operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP DELETE operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP OPTIONS operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP HEAD operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"]="Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__post__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
post
routing.py
def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP DELETE operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP OPTIONS operation. # Example ```python from fastapi import APIRouter, FastAPI app=FastAPI() router=APIRouter() @ router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP HEAD operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"]="Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__delete__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
delete
routing.py
def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__options__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
options
routing.py
def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__head__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
head
routing.py
def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP PATCH operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__patch__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
patch
routing.py
def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this * path operation*. For example, in `http: // example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic * field * type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/ docs`) will show it as the response(JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code(Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https: // fastapi.tiangolo.com/tutorial/response-model /) . """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https: // fastapi.tiangolo.com/tutorial/response-status-code /) . """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the * path operation*. 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 / # tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies(using `Depends()`) to be applied to the * path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https: // fastapi.tiangolo.com/tutorial/dependencies/dependencies-in -path-operation-decorators /) . """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the * path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the * path operation*. If not provided, it will be extracted automatically from the docstring of the * path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this * path operation*. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this * path operation * as deprecated. It will be added to the generated OpenAPI(e.g. visible at `/ docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this * path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class . 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler(less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https: // fastapi.tiangolo.com/tutorial/response-model / # response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this * path operation * in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this * path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https: // fastapi.tiangolo.com/advanced/custom-response / # redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this * path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of * path operations * that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this * path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https: // fastapi.tiangolo.com/advanced/path-operation-advanced-configuration / # custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a * path operation * using an HTTP TRACE operation. # Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None=None app=FastAPI() router=APIRouter() @ router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__trace__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
method
trace
routing.py
def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events /) . """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https: // fastapi.tiangolo.com/advanced/events/ # alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__routing__on_event__9293795e99afbda07d2744f1eb7d23d2f0ea0154
callee
fail-to-pass
https://github.com/fastapi/fastapi
9293795e99afbda07d2744f1eb7d23d2f0ea0154
method
on_event
routing.py
def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack from enum import Enum, IntEnum from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from pydantic.utils import lenient_issubclass from starlette import routing 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 from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp, Scope from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( res.__config__, "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) 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: try: body: Any = None if body_field: if is_body_form: body = await request.form() stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) 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: raise RequestValidationError( [ErrorWrapper(e, ("body", e.pos))], body=e.doc ) from e except HTTPException: raise except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_args: Dict[str, Any] = {"background": 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 sub_response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if sub_response.status_code: response_args["status_code"] = sub_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, ) 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(sub_response.headers.raw) return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = 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.path_regex, self.path_format, self.param_convertors = compile_path( path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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 self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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 if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] 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}" response_field = create_response_field( name=response_name, type_=model) 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) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) 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, ) 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): def __init__( self, *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack from enum import Enum, IntEnum from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.types import DecoratedCallable from fastapi.utils import ( create_cloned_field, create_response_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import ModelField, Undefined from pydantic.utils import lenient_issubclass from starlette import routing 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 from starlette.routing import Mount as Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp, Scope from starlette.websockets import WebSocket def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( res.__config__, "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return res.dict( by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[Union[SetIntStr, DictIntStrAny]] = None, exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) 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: try: body: Any = None if body_field: if is_body_form: body = await request.form() stack = request.scope.get("fastapi_astack") assert isinstance(stack, AsyncExitStack) 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: raise RequestValidationError( [ErrorWrapper(e, ("body", e.pos))], body=e.doc ) from e except HTTPException: raise except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_args: Dict[str, Any] = {"background": 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 sub_response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if sub_response.status_code: response_args["status_code"] = sub_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, ) 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(sub_response.headers.raw) return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = 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.path_regex, self.path_format, self.param_convertors = compile_path( path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) 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[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = 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 self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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 if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] 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}" response_field = create_response_field( name=response_name, type_=model) 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) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) 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, ) 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): def __init__( self, *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) or [] self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def on_event( self, event_type: str ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ______________ ERROR collecting tests/test_custom_route_class.py _______________ ImportError while importing test module '/workspace/test_repo/tests/test_custom_route_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_custom_route_class.py:2: in <module> from fastapi import APIRouter, FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_custom_route_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_custom_route_class.py
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_inherited_custom_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_inherited_custom_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.63s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py - NameError: name 'Field' is not d... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_inherited_custom_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_inherited_custom_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.59s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== ____________ ERROR collecting tests/test_inherited_custom_class.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_inherited_custom_class.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_inherited_custom_class.py:4: in <module> from fastapi import FastAPI fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_inherited_custom_class.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 2, 'passed': 1, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 1, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_inherited_custom_class.py
1_fastapi_callee__utils__is_body_allowed_for_status_code__c43120258fa89bc20d6f8ee671b6ead9ab223fc7
callee
fail-to-pass
https://github.com/fastapi/fastapi
c43120258fa89bc20d6f8ee671b6ead9ab223fc7
function
is_body_allowed_for_status_code
utils.py
def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304})
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})
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: if status_code is None: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 304}) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo() response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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) 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( WeakKeyDictionary() ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_regex_deprecated_body.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee__utils__get_path_param_names__b9d912c6380661647b51c322820fcb4ba08f32d2
callee
fail-to-pass
https://github.com/fastapi/fastapi
b9d912c6380661647b51c322820fcb4ba08f32d2
function
get_path_param_names
utils.py
def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path))
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions
import re from typing import Dict, Sequence, Set, Type from starlette.routing import BaseRoute from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseModel from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema def get_flat_models_from_routes(routes: Sequence[BaseRoute]): body_fields_from_routes = [] responses_from_routes = [] for route in routes: if route.include_in_schema and isinstance(route, routing.APIRoute): if route.body_field: assert isinstance( route.body_field, Field ), "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) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ): definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)}
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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 create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_regex_deprecated_body.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee__utils__create_cloned_field__aa84ac8e3e305d76e71c0c1b31237517948fa12f
callee
fail-to-pass
https://github.com/fastapi/fastapi
aa84ac8e3e305d76e71c0c1b31237517948fa12f
function
create_cloned_field
utils.py
def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} default = None, required = False, model_config = BaseConfig, schema = Schema(None), ) new_field.has_alias= field.has_alias new_field.alias= field.alias new_field.class_validators= field.class_validators new_field.default= field.default new_field.required= field.required new_field.model_config= field.model_config new_field.schema= field.schema new_field.allow_none= field.allow_none new_field.validate_always= field.validate_always if field.sub_fields: new_field.sub_fields= [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes( routes: Sequence[Type[BaseRoute]] ) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names fastapi/utils.py:109: in <module> def create_cloned_field(field: Field) -> Field: E NameError: name 'Field' is not defined =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py - NameError: name 'Field' is not de... !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee__utils__generate_operation_id_for_path__687065509b047a642acd1d281d6d68c6698509b1
callee
fail-to-pass
https://github.com/fastapi/fastapi
687065509b047a642acd1d281d6d68c6698509b1
function
generate_operation_id_for_path
utils.py
def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re from typing import Any, Dict, List, Sequence, Set, Type, cast from fastapi import routing from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, Schema, create_model from pydantic.fields import Field from pydantic.schema import get_flat_models_from_fields, model_process_schema from pydantic.utils import lenient_issubclass from starlette.routing import BaseRoute def get_flat_models_from_routes(routes: Sequence[BaseRoute]) -> Set[Type[BaseModel]]: body_fields_from_routes: List[Field] = [] responses_from_routes: List[Field] = [] 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, Field ), "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()) flat_models = get_flat_models_from_fields( body_fields_from_routes + responses_from_routes, known_models=set() ) return flat_models def get_model_definitions( *, flat_models: Set[Type[BaseModel]], model_name_map: Dict[Type[BaseModel], str] ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: m_schema, m_definitions = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def create_cloned_field(field: Field) -> Field: original_type = field.type_ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = create_model( # type: ignore original_type.__name__, __config__=original_type.__config__, __validators__=original_type.__validators__, ) for f in original_type.__fields__.values(): use_type.__fields__[f.name] = f new_field = Field( name=field.name, type_=use_type, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.schema = field.schema new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field(field.key_field) new_field.validators = field.validators new_field.whole_pre_validators = field.whole_pre_validators new_field.whole_post_validators = field.whole_post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field._populate_validators() return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = operation_id.replace( "{", "_").replace("}", "_").replace("/", "_") operation_id = operation_id + "_" + method.lower() return operation_id
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_regex_deprecated_body.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.61s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee__utils__generate_unique_id__8a0d4c79c18e6bd219b965b9d50578c139e7efd8
callee
fail-to-pass
https://github.com/fastapi/fastapi
8a0d4c79c18e6bd219b965b9d50578c139e7efd8
function
generate_unique_id
utils.py
def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id 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
import functools import re import warnings from dataclasses import is_dataclass from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.fields import FieldInfo, ModelField, UndefinedType from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: return response_field(field_info=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config new_field.field_info = field.field_info new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json new_field.shape = field.shape new_field.populate_validators() return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, stacklevel=2, ) operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) assert route.methods operation_id = 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 in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key] 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_regex_deprecated_body.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee__utils__deep_dict_update__181a32236a32305788b87d10e7990d9564ae2056
callee
fail-to-pass
https://github.com/fastapi/fastapi
181a32236a32305788b87d10e7990d9564ae2056
function
deep_dict_update
utils.py
def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
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
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id
import functools import re from dataclasses import is_dataclass from enum import Enum from typing import Any, Dict, Optional, Set, Type, Union, cast import fastapi from fastapi.logger import logger from fastapi.openapi.constants import REF_PREFIX from pydantic import BaseConfig, BaseModel, create_model from pydantic.class_validators import Validator from pydantic.schema import model_process_schema from pydantic.utils import lenient_issubclass try: from pydantic.fields import FieldInfo, ModelField, UndefinedType PYDANTIC_1 = True except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic.fields import Field as ModelField # type: ignore from pydantic import Schema as FieldInfo # type: ignore class UndefinedType: # type: ignore def __repr__(self) -> str: return "PydanticUndefined" logger.warning( "Pydantic versions < 1.0.0 are deprecated in FastAPI and support will be " "removed soon." ) PYDANTIC_1 = False # TODO: remove when removing support for Pydantic < 1.0.0 def get_field_info(field: ModelField) -> FieldInfo: if PYDANTIC_1: return field.field_info # type: ignore else: return field.schema # type: ignore # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 def warning_response_model_skip_defaults_deprecated() -> None: logger.warning( # pragma: nocover "response_model_skip_defaults has been deprecated in favor of " "response_model_exclude_unset to keep in line with Pydantic v1, support for " "it will be removed soon." ) def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict] = {} for model in flat_models: # ignore mypy error until enum schemas are released m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore ) definitions.update(m_definitions) model_name = model_name_map[model] definitions[model_name] = m_schema return definitions def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) def create_response_field( name: str, type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, required: Union[bool, UndefinedType] = False, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, ) -> ModelField: """ Create a new response field. Raises if type_ is invalid. """ class_validators = class_validators or {} field_info = field_info or FieldInfo(None) response_field = functools.partial( ModelField, name=name, type_=type_, class_validators=class_validators, default=default, required=required, model_config=model_config, alias=alias, ) try: if PYDANTIC_1: return response_field(field_info=field_info) else: # pragma: nocover return response_field(schema=field_info) except RuntimeError: raise fastapi.exceptions.FastAPIError( f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type" ) def create_cloned_field( field: ModelField, *, cloned_types: Dict[Type[BaseModel], Type[BaseModel]] = None, ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: cloned_types = dict() original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ # type: ignore use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_response_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias new_field.alias = field.alias new_field.class_validators = field.class_validators new_field.default = field.default new_field.required = field.required new_field.model_config = field.model_config if PYDANTIC_1: new_field.field_info = field.field_info else: # pragma: nocover new_field.schema = field.schema # type: ignore new_field.allow_none = field.allow_none new_field.validate_always = field.validate_always if field.sub_fields: new_field.sub_fields = [ create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields ] if field.key_field: new_field.key_field = create_cloned_field( field.key_field, cloned_types=cloned_types ) new_field.validators = field.validators if PYDANTIC_1: new_field.pre_validators = field.pre_validators new_field.post_validators = field.post_validators else: # pragma: nocover new_field.whole_pre_validators = field.whole_pre_validators # type: ignore new_field.whole_post_validators = field.whole_post_validators # type: ignore new_field.parse_json = field.parse_json new_field.shape = field.shape try: new_field.populate_validators() except AttributeError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 new_field._populate_validators() # type: ignore return new_field def generate_operation_id_for_path(*, name: str, path: str, method: str) -> str: operation_id = name + path operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def deep_dict_update(main_dict: dict, update_dict: dict) -> None: for key in update_dict: if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(update_dict[key], dict) ): deep_dict_update(main_dict[key], update_dict[key]) else: main_dict[key] = update_dict[key]
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model( original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] # type: ignore[attr-defined] new_field.class_validators = field.class_validators new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.validate_always = field.validate_always if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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 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
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from pydantic import BaseModel, create_model from pydantic.fields import FieldInfo from typing_extensions import Literal 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)) 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: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( annotation=type_, default=default, alias=alias ) else: field_info = field_info or FieldInfo() kwargs = {"name": name, "field_info": field_info} if PYDANTIC_V2: kwargs.update({"mode": mode}) else: kwargs.update( { "type_": type_, "class_validators": class_validators, "default": default, "required": required, "model_config": model_config, "alias": alias, } ) try: return ModelField(**kwargs) # type: ignore[arg-type] except (RuntimeError, PydanticSchemaGenerationError): raise fastapi.exceptions.FastAPIError( "Invalid args for response field! Hint: " f"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/" ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None, ) -> ModelField: if PYDANTIC_V2: return field # cloned_types caches already cloned types to support recursive models and improve # performance by avoiding unnecessary cloning if cloned_types is None: cloned_types = _CLONED_TYPES_CACHE original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ use_type = original_type if lenient_issubclass(original_type, BaseModel): original_type = cast(Type[BaseModel], original_type) use_type = cloned_types.get(original_type) if use_type is None: use_type = create_model(original_type.__name__, __base__=original_type) cloned_types[original_type] = use_type for f in original_type.__fields__.values(): use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] new_field.default = field.default # type: ignore[misc] new_field.required = field.required # type: ignore[misc] new_field.model_config = field.model_config # type: ignore[attr-defined] new_field.field_info = field.field_info new_field.allow_none = field.allow_none # type: ignore[attr-defined] new_field.validate_always = field.validate_always # type: ignore[attr-defined] if field.sub_fields: # type: ignore[attr-defined] new_field.sub_fields = [ # type: ignore[attr-defined] create_cloned_field(sub_field, cloned_types=cloned_types) for sub_field in field.sub_fields # type: ignore[attr-defined] ] if field.key_field: # type: ignore[attr-defined] new_field.key_field = create_cloned_field( # type: ignore[attr-defined] field.key_field, # type: ignore[attr-defined] cloned_types=cloned_types, ) new_field.validators = field.validators # type: ignore[attr-defined] new_field.pre_validators = field.pre_validators # type: ignore[attr-defined] new_field.post_validators = field.post_validators # type: ignore[attr-defined] new_field.parse_json = field.parse_json # type: ignore[attr-defined] new_field.shape = field.shape # type: ignore[attr-defined] new_field.populate_validators() # type: ignore[attr-defined] return new_field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( "fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", DeprecationWarning, 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
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== _____________ ERROR collecting tests/test_regex_deprecated_body.py _____________ ImportError while importing test module '/workspace/test_repo/tests/test_regex_deprecated_body.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_regex_deprecated_body.py:3: in <module> from fastapi import FastAPI, Form fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( fastapi/dependencies/utils.py:57: in <module> from fastapi.utils import create_response_field, get_path_param_names E ImportError: cannot import name 'create_response_field' from 'fastapi.utils' (/workspace/test_repo/fastapi/utils.py) =========================== short test summary info ============================ ERROR tests/test_regex_deprecated_body.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.60s ===============================
{'total': 4, 'passed': 4, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/utils.py
./test_repo/tests/test_regex_deprecated_body.py
1_fastapi_callee___compat__get_schema_from_model_field__0976185af96ab2ee39c949c0456be616b01f8669
callee
fail-to-pass
https://github.com/fastapi/fastapi
0976185af96ab2ee39c949c0456be616b01f8669
function
get_schema_from_model_field
_compat.py
def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return is_bytes_sequence_annotation(field.type_) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return type(field_info).from_annotation(annotation) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = ( get_origin( field.field_info.annotation) or field.field_info.annotation ) # type: ignore[arg-type] assert issubclass(origin_type, sequence_types) # type: ignore[no-any-return] return sequence_annotation_to_type[origin_type](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors()[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 else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.networks import ( # type: ignore[no-redef] MultiHostDsn as MultiHostUrl, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: # type: ignore[no-any-return,attr-defined] return sequence_shape_to_type[field.shape](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper( MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel 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 _normalize_errors(errors) ] return updated_loc_errors 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: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] 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: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return 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 ) assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] 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]: return [ ModelField(field_info=field_info, name=name) for name, field_info in model.model_fields.items() ] else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] for sub_field in field.sub_fields: # type: ignore[attr-defined] if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return list(model.__fields__.values()) # type: ignore[attr-defined] 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 _normalize_errors(errors) ] return updated_loc_errors 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)) # type: ignore[arg-type] 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)) 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) )
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 10 items tests/test_response_by_alias.py::test_read_dict PASSED [ 10%] tests/test_response_by_alias.py::test_read_model PASSED [ 20%] tests/test_response_by_alias.py::test_read_list PASSED [ 30%] tests/test_response_by_alias.py::test_read_dict_by_alias PASSED [ 40%] tests/test_response_by_alias.py::test_read_model_by_alias PASSED [ 50%] tests/test_response_by_alias.py::test_read_list_by_alias PASSED [ 60%] tests/test_response_by_alias.py::test_read_dict_no_alias PASSED [ 70%] tests/test_response_by_alias.py::test_read_model_no_alias PASSED [ 80%] tests/test_response_by_alias.py::test_read_list_no_alias PASSED [ 90%] tests/test_response_by_alias.py::test_openapi_schema FAILED [100%] =================================== FAILURES =================================== _____________________________ test_openapi_schema ______________________________ def test_openapi_schema(): > response = client.get("/openapi.json") tests/test_response_by_alias.py:150: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:551: in get return super().get( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1041: in get return self.request( ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:519: in request return super().request( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:814: in request return self.send(request, auth=auth, follow_redirects=follow_redirects) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:901: in send response = self._send_handling_auth( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:929: in _send_handling_auth response = self._send_handling_redirects( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:966: in _send_handling_redirects response = self._send_single_request(request) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1002: in _send_single_request response = transport.handle_request(request) ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:401: in handle_request raise exc ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:398: in handle_request portal.call(self.app, scope, receive, send) ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:277: in call return cast(T_Retval, self.start_task_soon(func, *args).result()) /usr/local/lib/python3.11/concurrent/futures/_base.py:456: in result return self.__get_result() /usr/local/lib/python3.11/concurrent/futures/_base.py:401: in __get_result raise self._exception ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:217: in _call_func retval = await retval fastapi/applications.py:1054: in __call__ await super().__call__(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/applications.py:123: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:186: in __call__ raise exc ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:164: in __call__ await self.app(scope, receive, _send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py:65: in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:754: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:774: in app await route.handle(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:295: in handle await self.app(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:77: in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:74: in app response = await f(request) fastapi/applications.py:1009: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:981: in openapi self.openapi_schema = get_openapi( fastapi/openapi/utils.py:483: in get_openapi result = get_openapi_path( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def get_openapi_path( *, route: routing.APIRoute, operation_ids: Set[str], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], 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) all_route_params = get_flat_params(route.dependant) operation_parameters = get_openapi_operation_parameters( all_route_params=all_route_params, schema_generator=schema_generator, 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, schema_generator=schema_generator, 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, schema_generator=schema_generator, 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, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) E TypeError: get_schema_from_model_field() got an unexpected keyword argument 'separate_input_output_schemas' fastapi/openapi/utils.py:322: TypeError =========================== short test summary info ============================ FAILED tests/test_response_by_alias.py::test_openapi_schema - TypeError: get_... ========================= 1 failed, 9 passed in 0.95s ==========================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 10, 'passed': 9, 'xpassed': 0, 'failed': 1, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
./test_repo/fastapi/_compat.py
./test_repo/tests/test_response_by_alias.py
1_fastapi_callee___compat__get_definitions__0976185af96ab2ee39c949c0456be616b01f8669
callee
fail-to-pass
https://github.com/fastapi/fastapi
0976185af96ab2ee39c949c0456be616b01f8669
function
get_definitions
_compat.py
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions
def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 MultiHostUrl as MultiHostUrl from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from pydantic_core.core_schema import ( general_plain_validator_function as general_plain_validator_function, ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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(), 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: inputs = [ (field, field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return is_bytes_sequence_annotation(field.type_) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return type(field_info).from_annotation(annotation) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = ( get_origin( field.field_info.annotation) or field.field_info.annotation ) # type: ignore[arg-type] assert issubclass(origin_type, sequence_types) # type: ignore[no-any-return] return sequence_annotation_to_type[origin_type](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors()[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 else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.networks import ( # type: ignore[no-redef] MultiHostDsn as MultiHostUrl, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def general_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: # type: ignore[attr-defined] return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: # type: ignore[no-any-return,attr-defined] return sequence_shape_to_type[field.shape](value) def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper( MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel 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 _normalize_errors(errors) ] return updated_loc_errors 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: return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[ 0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] # type: ignore[attr-defined] for sub_field in field.sub_fields: if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] 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: # type: ignore[arg-type] 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)) 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) )
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") sequence_annotation_to_type = { Sequence: list, List: list, list: list, Tuple: tuple, tuple: tuple, Set: set, set: set, FrozenSet: frozenset, frozenset: frozenset, Deque: deque, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter 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 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 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 ) Required = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @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: self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[self.field_info.annotation, self.field_info] ) 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 get_annotation_from_field_info( annotation: Any, field_info: FieldInfo, field_name: str ) -> Any: return annotation def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: return errors # type: ignore[return-value] def _model_rebuild(model: Type[BaseModel]) -> None: model.model_rebuild() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.model_dump(mode=mode, **kwargs) def _get_model_config(model: BaseModel) -> Any: return model.model_config def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, 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 else "validation" ) # 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_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: return {} def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: override_mode: Union[Literal["validation"], None] = ( None if separate_input_output_schemas else "validation" ) inputs = [ (field, override_mode or field.mode, field._type_adapter.core_schema) for field in fields ] field_mapping, definitions = schema_generator.generate_definitions( inputs=inputs ) return field_mapping, definitions # type: ignore[return-value] def is_scalar_field(field: ModelField) -> bool: from fastapi import params return field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return 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 ) assert issubclass(origin_type, sequence_types) # type: ignore[arg-type] return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return] 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]: return [ ModelField(field_info=field_info, name=name) for name, field_info in model.model_fields.items() ] else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 from pydantic import ( # type: ignore[assignment] BaseConfig as BaseConfig, # noqa: F401 ) from pydantic import ValidationError as ValidationError # noqa: F401 from pydantic.class_validators import ( # type: ignore[no-redef] Validator as Validator, # noqa: F401 ) from pydantic.error_wrappers import ( # type: ignore[no-redef] ErrorWrapper as ErrorWrapper, # noqa: F401 ) from pydantic.errors import MissingError from pydantic.fields import ( # type: ignore[attr-defined] SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, SHAPE_SINGLETON, SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS, ) from pydantic.fields import FieldInfo as FieldInfo from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Required as Required, # noqa: F401 ) from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) from pydantic.fields import ( # type: ignore[no-redef, attr-defined] UndefinedType as UndefinedType, # noqa: F401 ) from pydantic.schema import ( field_schema, get_flat_models_from_fields, get_model_name_map, model_process_schema, ) from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401 get_annotation_from_field_info as get_annotation_from_field_info, ) from pydantic.typing import ( # type: ignore[no-redef] evaluate_forwardref as evaluate_forwardref, # noqa: F401 ) from pydantic.utils import ( # type: ignore[no-redef] lenient_issubclass as lenient_issubclass, # noqa: F401 ) GetJsonSchemaHandler = Any # type: ignore[assignment,misc] JsonSchemaValue = Dict[str, Any] # type: ignore[misc] CoreSchema = Any # type: ignore[assignment,misc] sequence_shapes = { SHAPE_LIST, SHAPE_SET, SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, } sequence_shape_to_type = { SHAPE_LIST: list, SHAPE_SET: set, SHAPE_TUPLE: tuple, SHAPE_SEQUENCE: list, SHAPE_TUPLE_ELLIPSIS: list, } @dataclass class GenerateJsonSchema: # type: ignore[no-redef] ref_template: str class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef] pass def with_info_plain_validator_function( # type: ignore[misc] function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions( *, flat_models: Set[Union[Type[BaseModel], Type[Enum]]], model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str], ) -> Dict[str, Any]: definitions: Dict[str, Dict[str, Any]] = {} for model in flat_models: m_schema, m_definitions, m_nested_models = model_process_schema( model, model_name_map=model_name_map, ref_prefix=REF_PREFIX ) definitions.update(m_definitions) model_name = model_name_map[model] if "description" in m_schema: m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions def is_pv1_scalar_field(field: ModelField) -> bool: from fastapi import params field_info = field.field_info if not ( field.shape == SHAPE_SINGLETON # type: ignore[attr-defined] and not lenient_issubclass(field.type_, BaseModel) and not lenient_issubclass(field.type_, dict) and not field_annotation_is_sequence(field.type_) and not is_dataclass(field.type_) and not isinstance(field_info, params.Body) ): return False if field.sub_fields: # type: ignore[attr-defined] if not all( is_pv1_scalar_field(f) for f in field.sub_fields # type: ignore[attr-defined] ): return False return True def is_pv1_scalar_sequence_field(field: ModelField) -> bool: if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined] field.type_, BaseModel ): if field.sub_fields is not None: # type: ignore[attr-defined] for sub_field in field.sub_fields: # type: ignore[attr-defined] if not is_pv1_scalar_field(sub_field): return False return True if _annotation_is_sequence(field.type_): return True return False def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]: use_errors: List[Any] = [] for error in errors: if isinstance(error, ErrorWrapper): new_errors = ValidationError( # type: ignore[call-arg] errors=[error], model=RequestErrorModel ).errors() use_errors.extend(new_errors) elif isinstance(error, list): use_errors.extend(_normalize_errors(error)) else: use_errors.append(error) return use_errors def _model_rebuild(model: Type[BaseModel]) -> None: model.update_forward_refs() def _model_dump( model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any ) -> Any: return model.dict(**kwargs) def _get_model_config(model: BaseModel) -> Any: return model.__config__ # type: ignore[attr-defined] def get_schema_from_model_field( *, field: ModelField, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> Dict[str, Any]: # This expects that GenerateJsonSchema was already used to generate the definitions return field_schema( # type: ignore[no-any-return] field, model_name_map=model_name_map, ref_prefix=REF_PREFIX )[0] def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap: models = get_flat_models_from_fields(fields, known_models=set()) return get_model_name_map(models) # type: ignore[no-any-return] def get_definitions( *, fields: List[ModelField], schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> Tuple[ Dict[ Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], Dict[str, Dict[str, Any]], ]: models = get_flat_models_from_fields(fields, known_models=set()) return {}, get_model_definitions( flat_models=models, model_name_map=model_name_map ) def is_scalar_field(field: ModelField) -> bool: return is_pv1_scalar_field(field) def is_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined] def is_scalar_sequence_field(field: ModelField) -> bool: return is_pv1_scalar_sequence_field(field) def is_bytes_field(field: ModelField) -> bool: return lenient_issubclass(field.type_, bytes) def is_bytes_sequence_field(field: ModelField) -> bool: return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined] def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: return copy(field_info) def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined] def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg] new_error = ValidationError([missing_field_error], RequestErrorModel) return new_error.errors()[0] # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: BodyModel = create_model(model_name) for f in fields: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: return list(model.__fields__.values()) # type: ignore[attr-defined] 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 _normalize_errors(errors) ] return updated_loc_errors 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)) # type: ignore[arg-type] 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)) 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) )
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 10 items tests/test_response_by_alias.py::test_read_dict PASSED [ 10%] tests/test_response_by_alias.py::test_read_model PASSED [ 20%] tests/test_response_by_alias.py::test_read_list PASSED [ 30%] tests/test_response_by_alias.py::test_read_dict_by_alias PASSED [ 40%] tests/test_response_by_alias.py::test_read_model_by_alias PASSED [ 50%] tests/test_response_by_alias.py::test_read_list_by_alias PASSED [ 60%] tests/test_response_by_alias.py::test_read_dict_no_alias PASSED [ 70%] tests/test_response_by_alias.py::test_read_model_no_alias PASSED [ 80%] tests/test_response_by_alias.py::test_read_list_no_alias PASSED [ 90%] tests/test_response_by_alias.py::test_openapi_schema FAILED [100%] =================================== FAILURES =================================== _____________________________ test_openapi_schema ______________________________ def test_openapi_schema(): > response = client.get("/openapi.json") tests/test_response_by_alias.py:150: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:551: in get return super().get( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1041: in get return self.request( ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:519: in request return super().request( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:814: in request return self.send(request, auth=auth, follow_redirects=follow_redirects) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:901: in send response = self._send_handling_auth( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:929: in _send_handling_auth response = self._send_handling_redirects( ../test_venv/lib/python3.11/site-packages/httpx/_client.py:966: in _send_handling_redirects response = self._send_single_request(request) ../test_venv/lib/python3.11/site-packages/httpx/_client.py:1002: in _send_single_request response = transport.handle_request(request) ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:401: in handle_request raise exc ../test_venv/lib/python3.11/site-packages/starlette/testclient.py:398: in handle_request portal.call(self.app, scope, receive, send) ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:277: in call return cast(T_Retval, self.start_task_soon(func, *args).result()) /usr/local/lib/python3.11/concurrent/futures/_base.py:449: in result return self.__get_result() /usr/local/lib/python3.11/concurrent/futures/_base.py:401: in __get_result raise self._exception ../test_venv/lib/python3.11/site-packages/anyio/from_thread.py:217: in _call_func retval = await retval fastapi/applications.py:1054: in __call__ await super().__call__(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/applications.py:123: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:186: in __call__ raise exc ../test_venv/lib/python3.11/site-packages/starlette/middleware/errors.py:164: in __call__ await self.app(scope, receive, _send) ../test_venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py:65: in __call__ await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:754: in __call__ await self.middleware_stack(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:774: in app await route.handle(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:295: in handle await self.app(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:77: in app await wrap_app_handling_exceptions(app, request)(scope, receive, send) ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:64: in wrapped_app raise exc ../test_venv/lib/python3.11/site-packages/starlette/_exception_handler.py:53: in wrapped_app await app(scope, receive, sender) ../test_venv/lib/python3.11/site-packages/starlette/routing.py:74: in app response = await f(request) fastapi/applications.py:1009: in openapi return JSONResponse(self.openapi()) fastapi/applications.py:981: in openapi self.openapi_schema = get_openapi( _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 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, ) -> 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) schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) > field_mapping, definitions = get_definitions( fields=all_fields, schema_generator=schema_generator, model_name_map=model_name_map, separate_input_output_schemas=separate_input_output_schemas, ) E TypeError: get_definitions() got an unexpected keyword argument 'separate_input_output_schemas' fastapi/openapi/utils.py:475: TypeError =========================== short test summary info ============================ FAILED tests/test_response_by_alias.py::test_openapi_schema - TypeError: get_... ========================= 1 failed, 9 passed in 0.90s ==========================
{'total': 10, 'passed': 10, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 10, 'passed': 9, 'xpassed': 0, 'failed': 1, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
./test_repo/fastapi/_compat.py
./test_repo/tests/test_response_by_alias.py
1_fastapi_callee__routing___prepare_response_content__aea04ee32ee1942e6e1a904527bb8da6ba76abd9
callee
fail-to-pass
https://github.com/fastapi/fastapi
aea04ee32ee1942e6e1a904527bb8da6ba76abd9
function
_prepare_response_content
routing.py
def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res
def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def get_request_handler( dependant: Dependant, body_field: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import inspect from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.openapi.constants import STATUS_CODES_WITH_NO_BODY from fastapi.utils import ( PYDANTIC_1, create_cloned_field, create_response_field, generate_operation_id_for_path, get_field_info, warning_response_model_skip_defaults_deprecated, ) from pydantic import BaseModel from pydantic.error_wrappers import ErrorWrapper, ValidationError from starlette import routing 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 Mount # noqa from starlette.routing import ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket try: from pydantic.fields import FieldInfo, ModelField except ImportError: # pragma: nocover # TODO: remove when removing support for Pydantic < 1.0.0 from pydantic import Schema as FieldInfo # type: ignore from pydantic.fields import Field as ModelField # type: ignore def _prepare_response_content( res: Any, *, by_alias: bool = True, exclude_unset: bool ) -> Any: if isinstance(res, BaseModel): if PYDANTIC_1: return res.dict(by_alias=by_alias, exclude_unset=exclude_unset) else: return res.dict( by_alias=by_alias, skip_defaults=exclude_unset ) # pragma: nocover elif isinstance(res, list): return [ _prepare_response_content(item, exclude_unset=exclude_unset) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content(v, exclude_unset=exclude_unset) for k, v in res.items() } return res async def serialize_response( *, field: ModelField = None, response_content: Any, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, exclude_unset: bool = False, is_coroutine: bool = True, ) -> Any: if field: errors = [] response_content = _prepare_response_content( response_content, by_alias=by_alias, exclude_unset=exclude_unset ) 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_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, ) 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: ModelField = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: ModelField = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance( get_field_info(body_field), params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = 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, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, callbacks: Optional[List["APIRoute"]] = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: assert ( status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id self.response_field = create_response_field( name=response_name, type_=self.response_model ) # 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 be always created. 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.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 ( additional_status_code not in STATUS_CODES_WITH_NO_BODY ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_response_field( name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} 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.include_in_schema = include_in_schema self.response_class = response_class assert callable(endpoint), f"An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, default_response_class: Type[Response] = None, on_startup: Sequence[Callable] = None, on_shutdown: Sequence[Callable] = None, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: List[APIRoute] = None, ) -> None: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=callbacks, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), callbacks=route.callbacks, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = None, response_model_exclude_unset: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, callbacks: List[APIRoute] = None, ) -> Callable: if response_model_skip_defaults is not None: warning_response_model_skip_defaults_deprecated() # pragma: nocover return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=bool( response_model_exclude_unset or response_model_skip_defaults ), include_in_schema=include_in_schema, response_class=response_class or self.default_response_class, name=name, callbacks=callbacks, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________________ ERROR collecting tests/test_route_scope.py __________________ ImportError while importing test module '/workspace/test_repo/tests/test_route_scope.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_route_scope.py:2: in <module> from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_route_scope.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_route_scope.py
1_fastapi_callee__routing__get_request_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
function
get_request_handler
routing.py
def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app
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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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_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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________________ ERROR collecting tests/test_route_scope.py __________________ ImportError while importing test module '/workspace/test_repo/tests/test_route_scope.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_route_scope.py:2: in <module> from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_route_scope.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_route_scope.py
1_fastapi_callee__routing__get_websocket_app__b087246f2649e1b30545693d7b850e5f277c3a29
callee
fail-to-pass
https://github.com/fastapi/fastapi
b087246f2649e1b30545693d7b850e5f277c3a29
function
get_websocket_app
routing.py
def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**solved_result.values) return app
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging import re from typing import Any, Callable, Dict, List, Optional, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION from starlette.websockets import WebSocket def serialize_response(*, field: Field = None, response: Response) -> Any: encoded = jsonable_encoder(response) if field: errors = [] value, errors_ = field.validate(encoded, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors) return jsonable_encoder(value) else: return encoded def get_app( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e values, errors, background_tasks = await solve_dependencies( request=request, dependant=dependant, body=body ) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response ) return response_class( content=response_data, status_code=status_code, background=background_tasks, ) return app def get_websocket_app(dependant: Dependant) -> Callable: async def app(websocket: WebSocket) -> None: values, errors, _ = await solve_dependencies( request=websocket, dependant=dependant ) if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) assert dependant.call is not None, "dependant.call must me a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__(self, path: str, endpoint: Callable, *, name: str = None) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app(dependant=self.dependant)) regex = "^" + path + "$" regex = re.sub("{([a-zA-Z_][a-zA-Z0-9_]*)}", r"(?P<\1>[^/]+)", regex) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, ) -> None: assert path.startswith("/"), "Routed paths must always start with '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.response_model = response_model if self.response_model: assert lenient_issubclass( response_class, JSONResponse ), "To declare a type the response must be a JSON response" response_name = "Response_" + self.name self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) else: self.response_field = None self.status_code = status_code self.tags = tags or [] self.dependencies = dependencies or [] self.summary = summary self.description = description or inspect.cleandoc( self.endpoint.__doc__ or "") self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.name}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} self.deprecated = deprecated if methods is None: methods = ["GET"] self.methods = methods self.operation_id = operation_id self.include_in_schema = include_in_schema self.response_class = response_class self.path_regex, self.path_format, self.param_convertors = compile_path( path) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=path) ) self.body_field = get_body_field( dependant=self.dependant, name=self.name) self.app = request_response( get_app( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, ) ) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> None: route = APIRoute( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: List[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=(dependencies or []) + (route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, include_in_schema=route.include_in_schema, response_class=route.response_class, name=route.name, ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=route.methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[BaseModel] = None, status_code: int = 200, tags: List[str] = None, dependencies: List[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, include_in_schema: bool = True, response_class: Type[Response] = JSONResponse, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies or [], summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) return response return app 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________________ ERROR collecting tests/test_route_scope.py __________________ ImportError while importing test module '/workspace/test_repo/tests/test_route_scope.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_route_scope.py:2: in <module> from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_route_scope.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_route_scope.py
1_fastapi_callee__routing__decorator__406c092a3bf65bbd4405ce87611a7e0b9c0ae706
callee
fail-to-pass
https://github.com/fastapi/fastapi
406c092a3bf65bbd4405ce87611a7e0b9c0ae706
function
decorator
routing.py
def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func
def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import inspect import re import typing from copy import deepcopy from starlette import routing from starlette.routing import get_name, request_response from starlette.requests import Request from starlette.responses import Response, JSONResponse from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY from pydantic.fields import Field, Required from pydantic.schema import get_annotation_from_schema from pydantic import BaseConfig, BaseModel, create_model, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.errors import MissingError from pydantic.utils import lenient_issubclass from .pydantic_utils import jsonable_encoder from fastapi import params from fastapi.security.base import SecurityBase param_supported_types = (str, int, float, bool) class Dependant: def __init__( self, *, path_params: typing.List[Field] = None, query_params: typing.List[Field] = None, header_params: typing.List[Field] = None, cookie_params: typing.List[Field] = None, body_params: typing.List[Field] = None, dependencies: typing.List["Dependant"] = None, security_schemes: typing.List[Field] = None, name: str = None, call: typing.Callable = None, request_param_name: str = None, ) -> None: self.path_params: typing.List[Field] = path_params or [] self.query_params: typing.List[Field] = query_params or [] self.header_params: typing.List[Field] = header_params or [] self.cookie_params: typing.List[Field] = cookie_params or [] self.body_params: typing.List[Field] = body_params or [] self.dependencies: typing.List[Dependant] = dependencies or [] self.security_schemes: typing.List[Field] = security_schemes or [] self.request_param_name = request_param_name self.name = name self.call: typing.Callable = call def request_params_to_args( required_params: typing.List[Field], received_params: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] for field in required_params: value = received_params.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper(MissingError(), loc=field.alias, config=BaseConfig) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=(field.schema.in_.value, field.alias) ) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def request_body_to_args( required_params: typing.List[Field], received_body: typing.Dict[str, typing.Any] ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.List[ErrorWrapper]]: values = {} errors = [] if required_params: field = required_params[0] sub_key = getattr(field.schema, "sub_key", None) if len(required_params) == 1 and not sub_key: received_body = {field.alias: received_body} for field in required_params: value = received_body.get(field.alias) if value is None: if field.required: errors.append( ErrorWrapper( MissingError(), loc=("body", field.alias), config=BaseConfig ) ) else: values[field.name] = deepcopy(field.default) continue v_, errors_ = field.validate( value, values, loc=("body", field.alias)) if isinstance(errors_, ErrorWrapper): errors_: ErrorWrapper errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) else: values[field.name] = v_ return values, errors def add_param_to_fields( *, param: inspect.Parameter, dependant: Dependant, default_schema=params.Param, force_type: params.ParamTypes = None, ): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, params.Param): schema = default_value default_value = schema.default if schema.in_ is None: schema.in_ = default_schema.in_ if force_type: schema.in_ = force_type else: schema = default_schema(default_value) required = default_value == Required annotation = typing.Any if not param.annotation == param.empty: annotation = param.annotation annotation = get_annotation_from_schema(annotation, schema) Config = BaseConfig field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=Config, class_validators=[], schema=schema, ) if schema.in_ == params.ParamTypes.path: dependant.path_params.append(field) elif schema.in_ == params.ParamTypes.query: dependant.query_params.append(field) elif schema.in_ == params.ParamTypes.header: dependant.header_params.append(field) else: assert ( schema.in_ == params.ParamTypes.cookie ), f"non-body parameters must be in path, query, header or cookie: {param.name}" dependant.cookie_params.append(field) def add_param_to_body_fields(*, param: inspect.Parameter, dependant: Dependant): default_value = Required if not param.default == param.empty: default_value = param.default if isinstance(default_value, Schema): schema = default_value default_value = schema.default else: schema = Schema(default_value) required = default_value == Required annotation = get_annotation_from_schema(param.annotation, schema) field = Field( name=param.name, type_=annotation, default=None if required else default_value, alias=schema.alias or param.name, required=required, model_config=BaseConfig, class_validators=[], schema=schema, ) dependant.body_params.append(field) def get_sub_dependant( *, param: inspect.Parameter, path: str ): depends: params.Depends = param.default if depends.dependency: dependency = depends.dependency else: dependency = param.annotation assert callable(dependency) sub_dependant = get_dependant(path=path, call=dependency, name=param.name) if isinstance(dependency, SecurityBase): sub_dependant.security_schemes.append(dependency) return sub_dependant def get_flat_dependant(dependant: Dependant): 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(), security_schemes=dependant.security_schemes.copy(), ) for sub_dependant in dependant.dependencies: if sub_dependant is dependant: raise ValueError("recursion", dependant.dependencies) flat_sub = get_flat_dependant(sub_dependant) 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.security_schemes.extend(flat_sub.security_schemes) return flat_dependant def get_path_param_names(path: str): return {item.strip("{}") for item in re.findall("{[^}]*}", path)} def get_dependant(*, path: str, call: typing.Callable, name: str = None): path_param_names = get_path_param_names(path) endpoint_signature = inspect.signature(call) signature_params = endpoint_signature.parameters dependant = Dependant(call=call, name=name) for param_name in signature_params: param = signature_params[param_name] if isinstance(param.default, params.Depends): sub_dependant = get_sub_dependant(param=param, path=path) dependant.dependencies.append(sub_dependant) for param_name in signature_params: param = signature_params[param_name] if ( (param.default == param.empty) or isinstance( param.default, params.Path) ) and (param_name in path_param_names): assert lenient_issubclass( param.annotation, param_supported_types ), f"Path params must be of type str, int, float or boot: {param}" param = signature_params[param_name] add_param_to_fields( param=param, dependant=dependant, default_schema=params.Path, force_type=params.ParamTypes.path, ) elif (param.default == param.empty or param.default is None) and ( param.annotation == param.empty or lenient_issubclass(param.annotation, param_supported_types) ): add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif isinstance(param.default, params.Param): if param.annotation != param.empty: assert lenient_issubclass( param.annotation, param_supported_types ), f"Parameters for Path, Query, Header and Cookies must be of type str, int, float or bool: {param}" add_param_to_fields( param=param, dependant=dependant, default_schema=params.Query ) elif lenient_issubclass(param.annotation, Request): dependant.request_param_name = param_name elif not isinstance(param.default, params.Depends): add_param_to_body_fields(param=param, dependant=dependant) return dependant def is_coroutine_callable(call: typing.Callable): if inspect.isfunction(call): return asyncio.iscoroutinefunction(call) elif inspect.isclass(call): return False else: call = getattr(call, "__call__", None) if not call: return False else: return asyncio.iscoroutinefunction(call) async def solve_dependencies(*, request: Request, dependant: Dependant): values = {} errors = [] for sub_dependant in dependant.dependencies: sub_values, sub_errors = await solve_dependencies( request=request, dependant=sub_dependant ) if sub_errors: return {}, errors if is_coroutine_callable(sub_dependant.call): solved = await sub_dependant.call(**sub_values) else: solved = await run_in_threadpool(sub_dependant.call, **sub_values) values[sub_dependant.name] = 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 = await request.json() body_values, body_errors = request_body_to_args( dependant.body_params, body) values.update(body_values) errors.extend(body_errors) if dependant.request_param_name: values[dependant.request_param_name] = request return values, errors def get_app(dependant: Dependant): is_coroutine = asyncio.iscoroutinefunction(dependant.call) async def app(request: Request) -> Response: values, errors = await solve_dependencies(request=request, dependant=dependant) if errors: errors_out = ValidationError(errors) raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail=errors_out.errors() ) else: if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): return raw_response else: return JSONResponse(content=jsonable_encoder(raw_response)) return app def get_openapi_params(dependant: Dependant): flat_dependant = get_flat_dependant(dependant) return ( flat_dependant.path_params + flat_dependant.query_params + flat_dependant.header_params + flat_dependant.cookie_params ) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: typing.Callable, *, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: # TODO define how to read and provide security params, and how to have them globally too # TODO implement dependencies and injection # TODO refactor code structure # TODO create testing # TODO testing coverage assert path.startswith("/"), "Routed paths must always start '/'" self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.include_in_schema = include_in_schema self.tags = tags self.summary = summary self.description = description self.operation_id = operation_id self.deprecated = deprecated self.request_body: typing.Union[BaseModel, Field, None] = None self.response_description = response_description self.response_code = response_code self.response_wrapper = response_wrapper self.response_field = None if response_type: assert lenient_issubclass( response_wrapper, JSONResponse ), "To declare a type the response must be a JSON response" self.response_type = response_type response_name = "Response_" + self.name self.response_field = Field( name=response_name, type_=self.response_type, class_validators=[], default=None, required=False, model_config=BaseConfig(), schema=Schema(None), ) else: self.response_type = None if methods is None: methods = ["GET"] self.methods = methods self.path_regex, self.path_format, self.param_convertors = self.compile_path( path ) assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant(path=path, call=self.endpoint) # flat_dependant = get_flat_dependant(self.dependant) # path_param_names = get_path_param_names(path) # for path_param in path_param_names: # assert path_param in { # f.alias for f in flat_dependant.path_params # }, f"Path parameter must be defined as a function parameter or be defined by a dependency: {path_param}" if self.dependant.body_params: first_param = self.dependant.body_params[0] sub_key = getattr(first_param.schema, "sub_key", None) if len(self.dependant.body_params) == 1 and not sub_key: self.request_body = first_param else: model_name = "Body_" + self.name BodyModel = create_model(model_name) for f in self.dependant.body_params: BodyModel.__fields__[f.name] = f required = any( True for f in self.dependant.body_params if f.required) field = Field( name="body", type_=BodyModel, default=None, required=required, model_config=BaseConfig, class_validators=[], alias="body", schema=Schema(None), ) self.request_body = field self.app = request_response(get_app(dependant=self.dependant)) class APIRouter(routing.Router): def add_api_route( self, path: str, endpoint: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> None: route = APIRoute( path, endpoint=endpoint, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) self.routes.append(route) def api_route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_api_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) return func return decorator def get( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["GET"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def put( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PUT"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def post( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["POST"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def delete( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["DELETE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def options( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["OPTIONS"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def head( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["HEAD"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def patch( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["PATCH"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, ) def trace( self, path: str, name: str = None, include_in_schema: bool = True, tags: typing.List[str] = [], summary: str = None, description: str = None, operation_id: str = None, deprecated: bool = None, response_type: typing.Type = None, response_description: str = "Successful Response", response_code=200, response_wrapper=JSONResponse, ): return self.api_route( path=path, methods=["TRACE"], name=name, include_in_schema=include_in_schema, tags=tags, summary=summary, description=description, operation_id=operation_id, deprecated=deprecated, response_type=response_type, response_description=response_description, response_code=response_code, response_wrapper=response_wrapper, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________________ ERROR collecting tests/test_route_scope.py __________________ ImportError while importing test module '/workspace/test_repo/tests/test_route_scope.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_route_scope.py:2: in <module> from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_route_scope.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.62s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_route_scope.py
1_fastapi_callee__routing__get_route_handler__8c3ef76139590e0478e799375ec4c41703ea9f77
callee
fail-to-pass
https://github.com/fastapi/fastapi
8c3ef76139590e0478e799375ec4c41703ea9f77
method
get_route_handler
routing.py
def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, )
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, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import inspect import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union from fastapi import params from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( get_body_field, get_dependant, get_parameterless_sub_dependant, solve_dependencies, ) from fastapi.encoders import DictIntStrAny, SetIntStr, jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import create_cloned_field, generate_operation_id_for_path from pydantic import BaseConfig, BaseModel, Schema from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.fields import Field from pydantic.utils import lenient_issubclass from starlette import routing 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 ( compile_path, get_name, request_response, websocket_session, ) from starlette.status import WS_1008_POLICY_VIOLATION from starlette.types import ASGIApp from starlette.websockets import WebSocket def serialize_response( *, field: Field = None, response: Response, include: Union[SetIntStr, DictIntStrAny] = None, exclude: Union[SetIntStr, DictIntStrAny] = set(), by_alias: bool = True, skip_defaults: bool = False, ) -> Any: if field: errors = [] if skip_defaults and isinstance(response, BaseModel): response = response.dict(skip_defaults=skip_defaults) value, errors_ = field.validate(response, {}, loc=("response",)) if isinstance(errors_, ErrorWrapper): errors.append(errors_) elif isinstance(errors_, list): errors.extend(errors_) if errors: raise ValidationError(errors, field.type_) return jsonable_encoder( value, include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, ) else: return jsonable_encoder(response) def get_request_handler( dependant: Dependant, body_field: Field = None, status_code: int = 200, response_class: Type[Response] = JSONResponse, response_field: Field = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, dependency_overrides_provider: Any = None, ) -> Callable: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) is_body_form = body_field and isinstance(body_field.schema, params.Form) async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logging.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors) else: assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: raw_response = await dependant.call(**values) else: raw_response = await run_in_threadpool(dependant.call, **values) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = serialize_response( field=response_field, response=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, skip_defaults=response_model_skip_defaults, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any = None ) -> Callable: async def app(websocket: WebSocket) -> None: solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, _, _2, _3 = solved_result if errors: await websocket.close(code=WS_1008_POLICY_VIOLATION) raise WebSocketRequestValidationError(errors) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable, *, name: str = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependant = get_dependant(path=path, call=self.endpoint) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, ) ) self.path_regex, self.path_format, self.param_convertors = compile_path( path) class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, name: str = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Optional[Type[Response]] = None, dependency_overrides_provider: Any = None, ) -> None: self.path = path self.endpoint = endpoint 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([method.upper() for method in methods]) self.unique_id = generate_operation_id_for_path( name=self.name, path=self.path_format, method=list(methods)[0] ) self.response_model = response_model if self.response_model: response_name = "Response_" + self.unique_id self.response_field: Optional[Field] = Field( name=response_name, type_=self.response_model, class_validators={}, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) # 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 be always created. self.secure_cloned_response_field: Optional[Field] = create_cloned_field( self.response_field ) else: self.response_field = None self.secure_cloned_response_field = None self.status_code = status_code self.tags = tags or [] if dependencies: self.dependencies = list(dependencies) else: self.dependencies = [] self.summary = summary 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] self.response_description = response_description self.responses = responses or {} 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 lenient_issubclass( model, BaseModel ), "A response model must be a Pydantic model" response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = Field( name=response_name, type_=model, class_validators=None, default=None, required=False, model_config=BaseConfig, schema=Schema(None), ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], Field] = response_fields else: self.response_fields = {} 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_skip_defaults = response_model_skip_defaults self.include_in_schema = include_in_schema self.response_class = response_class assert inspect.isfunction(endpoint) or inspect.ismethod( endpoint ), f"An endpoint must be a function or method" self.dependant = get_dependant( path=self.path_format, call=self.endpoint) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant( depends=depends, path=self.path_format), ) self.body_field = get_body_field( dependant=self.dependant, name=self.unique_id) self.dependency_overrides_provider = dependency_overrides_provider self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class or JSONResponse, 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_skip_defaults=self.response_model_skip_defaults, dependency_overrides_provider=self.dependency_overrides_provider, ) class APIRouter(routing.Router): def __init__( self, routes: List[routing.BaseRoute] = None, redirect_slashes: bool = True, default: ASGIApp = None, dependency_overrides_provider: Any = None, route_class: Type[APIRoute] = APIRoute, ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default ) self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class def add_api_route( self, path: str, endpoint: Callable, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: Optional[Union[Set[str], List[str]]] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, route_class_override: Optional[Type[APIRoute]] = None, ) -> None: route_class = route_class_override or self.route_class route = route_class( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, methods: List[str] = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable, name: str = None ) -> None: route = APIWebSocketRoute(path, endpoint=endpoint, name=name) self.routes.append(route) def websocket(self, path: str, name: str = None) -> Callable: def decorator(func: Callable) -> Callable: self.add_api_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: "APIRouter", *, prefix: str = "", tags: List[str] = None, dependencies: Sequence[params.Depends] = None, responses: Dict[Union[int, str], Dict[str, Any]] = None, default_response_class: Optional[Type[Response]] = None, ) -> None: if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") name = getattr(r, "name", "unknown") if path is not None and not path: raise Exception( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=(route.tags or []) + (tags or []), dependencies=list(dependencies or []) + list(route.dependencies or []), summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_skip_defaults=route.response_model_skip_defaults, include_in_schema=route.include_in_schema, response_class=route.response_class or default_response_class, name=route.name, route_class_override=type(route), ) elif isinstance(route, routing.Route): self.add_route( prefix + route.path, route.endpoint, methods=list(route.methods or []), include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): self.add_api_websocket_route( prefix + route.path, route.endpoint, name=route.name ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) def get( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def put( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def post( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def delete( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def options( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def head( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def patch( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, ) def trace( self, path: str, *, response_model: Type[Any] = None, status_code: int = 200, tags: List[str] = None, dependencies: Sequence[params.Depends] = None, summary: str = None, description: str = None, response_description: str = "Successful Response", responses: Dict[Union[int, str], Dict[str, Any]] = None, deprecated: bool = None, operation_id: str = None, response_model_include: Union[SetIntStr, DictIntStrAny] = None, response_model_exclude: Union[SetIntStr, DictIntStrAny] = set(), response_model_by_alias: bool = True, response_model_skip_defaults: bool = False, include_in_schema: bool = True, response_class: Type[Response] = None, name: str = None, ) -> Callable: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags or [], dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses or {}, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_skip_defaults=response_model_skip_defaults, include_in_schema=include_in_schema, response_class=response_class, name=name, )
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr( _get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field( name=response_name, type_=model) 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) 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 __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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, ) from fastapi import params from fastapi._compat import ( ModelField, Undefined, _get_model_config, _model_dump, _normalize_errors, 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 ( FastAPIError, 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 pydantic import BaseModel from starlette import routing 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, request_response, websocket_session, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( res: Any, *, exclude_unset: bool, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: if isinstance(res, BaseModel): read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None) if read_with_orm_mode: # Let from_orm extract the data from this model instead of converting # it now to a dict. # Otherwise, there's no way to extract lazy data that requires attribute # access instead of dict iteration, e.g. lazy relationships. return res return _model_dump( res, by_alias=True, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) elif isinstance(res, list): return [ _prepare_response_content( item, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for item in res ] elif isinstance(res, dict): return { k: _prepare_response_content( v, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) for k, v in res.items() } elif dataclasses.is_dataclass(res): return dataclasses.asdict(res) return res 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] 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, ) -> Any: if field: errors = [] if not hasattr(field, "serialize"): # pydantic v1 response_content = _prepare_response_content( response_content, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) 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_) elif errors_: errors.append(errors_) if errors: raise ResponseValidationError( errors=_normalize_errors(errors), body=response_content ) if hasattr(field, "serialize"): return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) return jsonable_encoder( 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 = asyncio.iscoroutinefunction(dependant.call) 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 async with AsyncExitStack() as file_stack: 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, ) 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 errors: List[Any] = [] async with AsyncExitStack() as async_exit_stack: 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, ) 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( _normalize_errors(errors), body=body ) raise validation_error if response is None: raise FastAPIError( "No response object was returned. 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" ) 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: async with AsyncExitStack() as async_exit_stack: # TODO: remove this scope later, after a few releases # This scope fastapi_astack is no longer used by FastAPI, kept for # compatibility, just in case websocket.scope["fastapi_astack"] = async_exit_stack 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( _normalize_errors(solved_result.errors) ) 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) 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 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}" response_field = create_model_field(name=response_name, type_=model) 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) 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 [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, 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, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Optional[Lifespan[Any]], 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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 this router in the generated OpenAPI. 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-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function def route( self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( 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, 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 ), name: Optional[str] = None, route_class_override: Optional[Type[APIRoute]] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Union[ Callable[[APIRoute], str], DefaultPlaceholder ] = Default(generate_unique_id), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[IncEx] = None, response_model_exclude: Optional[IncEx] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None, *, dependencies: Optional[Sequence[params.Depends]] = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ Optional[str], Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Decorate a WebSocket function. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). **Example** ## Example ```python from fastapi import APIRouter, FastAPI, WebSocket app = FastAPI() router = APIRouter() @router.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") app.include_router(router) ``` """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: Union[str, None] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, 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, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* in this router as deprecated. 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( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[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), ) -> None: """ Include another `APIRouter` in the same current `APIRouter`. Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() internal_router = APIRouter() users_router = APIRouter() @users_router.get("/users/") def read_users(): return [{"name": "Rick"}, {"name": "Morty"}] internal_router.include_router(users_router) app.include_router(internal_router) ``` """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: List[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP GET operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/items/") def read_items(): return [{"name": "Empanada"}, {"name": "Arepa"}] app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PUT operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.put("/items/{item_id}") def replace_item(item_id: str, item: Item): return {"message": "Item replaced", "id": item_id} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP POST operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.post("/items/") def create_item(item: Item): return {"message": "Item created"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP DELETE operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.delete("/items/{item_id}") def delete_item(item_id: str): return {"message": "Item deleted"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP OPTIONS operation. ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.options("/items/") def get_item_options(): return {"additions": ["Aji", "Guacamole"]} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP HEAD operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.head("/items/", status_code=204) def get_items_headers(response: Response): response.headers["X-Cat-Dog"] = "Alone in the world" app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP PATCH operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.patch("/items/") def update_item(item: Item): return {"message": "Item updated in place"} app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ Optional[int], Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ Optional[List[Union[str, Enum]]], Doc( """ A list of tags to be applied to the *path operation*. 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/#tags). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ Optional[str], Doc( """ A summary for the *path operation*. 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, description: Annotated[ Optional[str], Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. 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, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ Optional[Dict[Union[int, str], Dict[str, Any]]], Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ Optional[str], Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. 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). """ ), ] = None, response_model_include: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ Optional[IncEx], Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. 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-from-openapi). """ ), ] = True, response_class: Annotated[ Type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ Optional[str], Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ Optional[List[BaseRoute]], Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. 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, openapi_extra: Annotated[ Optional[Dict[str, Any]], Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[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), ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add a *path operation* using an HTTP TRACE operation. ## Example ```python from fastapi import APIRouter, FastAPI from pydantic import BaseModel class Item(BaseModel): name: str description: str | None = None app = FastAPI() router = APIRouter() @router.trace("/items/{item_id}") def trace_item(item_id: str): return None app.include_router(router) ``` """ return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: """ Add an event handler for the router. `on_event` is deprecated, use `lifespan` event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
============================= test session starts ============================== platform linux -- Python 3.11.9, pytest-8.3.2, pluggy-1.5.0 -- /workspace/test_venv/bin/python cachedir: .pytest_cache rootdir: /workspace/test_repo configfile: pyproject.toml plugins: anyio-3.7.1, asyncio-0.24.0 asyncio: mode=Mode.STRICT, default_loop_scope=function collecting ... collected 0 items / 1 error ==================================== ERRORS ==================================== __________________ ERROR collecting tests/test_route_scope.py __________________ ImportError while importing test module '/workspace/test_repo/tests/test_route_scope.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /usr/local/lib/python3.11/importlib/__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_route_scope.py:2: in <module> from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect fastapi/__init__.py:7: in <module> from .applications import FastAPI as FastAPI fastapi/applications.py:16: in <module> from fastapi import routing fastapi/routing.py:35: in <module> from fastapi.dependencies.utils import ( E ImportError: cannot import name '_should_embed_body_fields' from 'fastapi.dependencies.utils' (/workspace/test_repo/fastapi/dependencies/utils.py) =========================== short test summary info ============================ ERROR tests/test_route_scope.py !!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!! =============================== 1 error in 0.58s ===============================
{'total': 5, 'passed': 5, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 0}
{'total': 1, 'passed': 0, 'xpassed': 0, 'failed': 0, 'xfailed': 0, 'deselected': 0, 'skipped': 0, 'warning': 0, 'error': 1}
./test_repo/fastapi/routing.py
./test_repo/tests/test_route_scope.py